我有一个复杂的数据,我想简化它的结构。
这个数组深度可能会改变,因为它是来自外部资源的动态数据。我想将所有具有关键字price
的数组合并为一维数组。
我想把这个:
array(
'first_name' => 'John',
'last_name' => 'Due',
'product' => array(
'title' => 'Product #1',
'price' => '90',
'product' => array(
'title' => 'Product #2',
'price' => '90',
'product' => array(
'title' => 'Product #3',
'price' => '90',
),
),
),
'misc' => array(
'country' => 'United States',
array(
'product' => array(
'title' => 'Product #4',
'price' => '90',
),
)
),
array(
'title' => 'Product #5',
'price' => '90',
)
);
进入:
array(
array(
'title' => 'Product #1',
'price' => '90',
),
array(
'title' => 'Product #2',
'price' => '90',
),
array(
'title' => 'Product #3',
'price' => '90',
),
array(
'title' => 'Product #4',
'price' => '90',
),
array(
'title' => 'Product #5',
'price' => '90',
),
);
我想一个简单的方法是使用array_walk_recursive
,但发现我无法访问父数组。
array_walk_recursive(
$array,
function( $value, $key ) {
if ( 'price' === $key ) {
// cannot access the parent array
}
}
);
$array = array(
'first_name' => 'John',
'last_name' => 'Duei',
'product' => array(
'title' => 'Product #1',
'price' => '90',
'product' => array(
'title' => 'Product #2',
'price' => '90',
'product' => array(
'title' => 'Product #3',
'price' => '90',
),
),
),
'misc' => array(
'country' => 'United States',
array(
'product' => array(
'title' => 'Product #4',
'price' => '90',
),
)
),
array(
'title' => 'Product #5',
'price' => '90',
)
);
function array_walk_recursive_full($array, $callback)
{
if (!is_array($array)) return;
foreach ($array as $key => $value) {
$callback($value, $key);
array_walk_recursive_full($value, $callback);
}
}
$result = [];
array_walk_recursive_full(
$array,
function ($value, $key) use (&$result) {
if (isset($value['price'])) {
$result[] = [
'title' => $value['title'],
'price' => $value['price'],
];
}
}
);
print_r($result);
这里的工作代码示例