【问题标题】:Parse array to get required data解析数组以获取所需数据
【发布时间】:2015-10-21 11:27:50
【问题描述】:

我有一个这样的输入数组:

Array
(
    [one] => one
    [two] => two
    [group1] => Array
        (
            [three] => three
            [four] => four
            [group2] => Array
                (
                    [five] => five
                )

        )

    [group3] => Array
        (
            [six] => six
        )

)

我想从上面的数组中提取以下 6 个字符串:

Array
(
    [0] => one
    [1] => two
    [2] => group1,three
    [3] => group1,four
    [4] => group1,group2,five
    [5] => group3,six
)

有什么想法吗?有什么有用的PHP函数吗?

我尝试过这样的事情:

function getStrings( $data, &$result, $parent = '' ) {

    foreach( $data as $key => $value ) {

        if( is_array( $value ) ) {

            getStrings( $value, $result, $key );

        } else {

            if( $parent == '' ) {
                $result[] = $value;
            } else {
                $result[] = $parent . ',' . $value;
            }
        }
    }

}

$tree = array();
getStrings( $input, $tree );
print_r( $tree );

结果

Array
(
    [0] => one
    [1] => two
    [2] => group1,three
    [3] => group1,four
    [4] => group2,five
    [5] => group3,six
)

【问题讨论】:

  • 尝试使用嵌套的for循环
  • 你之前绑定的任何代码?
  • "gimme teh codez" 不会给你解决方案。展示你的作品。
  • @Pred 在目前的状态下,它不适合任何网站,包括代码审查。

标签: php arrays string


【解决方案1】:

根据你的数据结构是:

$data = [
    'one' => 'one',
    'two' => 'two',
    'group1' => [
        'three' => 'three',
        'four' => 'four',
        'group2' => ['five']
    ],
    'group3' => ['six' => 'six']
];

你可以使用递归函数:

function make_implode($data){
    $rows = [];
    foreach($data as $key => $val) {
        if(is_array($val)) {
            //$rows[] = $key;
            $nestedData = make_implode($val);
            if(is_array($nestedData)){
                foreach($nestedData as $keyNested => $valNested) {
                    $rows[] = $key.','.$valNested;
                }
            } else {
                $rows[] = $key.','.$nestedData;
            }

        } else {
            $rows[] = $val;
        }
    }

    return $rows;
}

$data = make_implode($data);
echo '<pre>'.print_r($data,1).'</pre>';


  //prints
Array
(
    [0] => one
    [1] => two
    [2] => group1,three
    [3] => group1,four
    [4] => group1,group2,five
    [5] => group3,six
)

【讨论】:

  • 感谢您的努力。
【解决方案2】:

使用递归函数,类似于:

$a = array("one"=>"one","group1"=>array("three"=>"three"));
var_dump($a);
function recFor($a) {
    foreach($a as $k => $v) {
        if(is_array($v)) {
            $tmp= recFor($v);
            $res[] = $tmp[0];
        } else {
            $res[] = $v;
        }
    }
    return $res;
}
$b = recFor($a);
var_dump($b);

这只是一个简单粗暴的例子,但你应该明白。

【讨论】:

  • 感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多