Php 在考虑父键的同时展平数组
我需要展平阵列,同时确保没有重复的关键点 例如,假设我有:Php 在考虑父键的同时展平数组,php,Php,我需要展平阵列,同时确保没有重复的关键点 例如,假设我有: $arr = array( $foo = array( 'donuts' => array( 'name' => 'lionel ritchie', 'animal' => 'manatee', ) ) ); 我需要一个扁平阵列,如下所示: $arr = array( 'donuts na
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
我需要一个扁平阵列,如下所示:
$arr = array(
'donuts name' => 'lionel ritchie',
'donuts animal' => 'manatee',
);
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
// Will loop 'donuts' and other items that you can insert in the $foo array.
foreach($foo as $findex => $child) {
// Remove item 'donuts' from array, it will get the numeric key of current element by using array_search and array_keys
array_splice($foo, array_search($findex, array_keys($foo)), 1);
foreach($child as $index => $value) {
// Adds an array element for every child
$foo[$findex.' '.$index] = $value;
}
}
它需要工作,即使我们有超过1个父密钥
我有以下代码,但我不确定我是否可以使用它
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)) as $k=>$v){
$array1c[$k] = $v;
}
做起来很简单,就这样做:
$arr = array(
'donuts name' => 'lionel ritchie',
'donuts animal' => 'manatee',
);
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
// Will loop 'donuts' and other items that you can insert in the $foo array.
foreach($foo as $findex => $child) {
// Remove item 'donuts' from array, it will get the numeric key of current element by using array_search and array_keys
array_splice($foo, array_search($findex, array_keys($foo)), 1);
foreach($child as $index => $value) {
// Adds an array element for every child
$foo[$findex.' '.$index] = $value;
}
}
var\u转储的结果($foo)代码>将是:
array(2) {
["donuts name"]=>
string(14) "lionel ritchie"
["donuts animal"]=>
string(7) "manatee"
}
试试看:)它不应该是递归的吗?假设我们有10个父对象。是的,试着创建一个递归执行这些操作的函数。