我有一个像这样的输入数组:
utc
我想从上面的数组中提取以下6个字符串:
Array
(
[one] => one
[two] => two
[group1] => Array
(
[three] => three
[four] => four
[group2] => Array
(
[five] => five
)
)
[group3] => Array
(
[six] => six
)
)
任何想法?这有什么有用的PHP函数吗?
我尝试过这样的事情:
Array
(
[0] => one
[1] => two
[2] => group1,three
[3] => group1,four
[4] => group1,group2,five
[5] => group3,six
)
结果:
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 );
答案 0 :(得分:1)
使用递归函数,类似于:
$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);
这只是一个快速而肮脏的例子,但你应该明白这一点。
答案 1 :(得分: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
)