我有一个要简化的复杂数据。
此数组深度可能会更改,因为它是来自外部资源的动态数据。
我想将所有具有键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
}
}
);
答案 0 :(得分:2)
$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);