Php 合并并重新排列嵌套的键/值
我有这样一个数组:Php 合并并重新排列嵌套的键/值,php,arrays,Php,Arrays,我有这样一个数组: array( 0 => array( 'name' => 'colors', 'options' => array( array('name'=>'red', 'price'=>'2'), array('name'=>'blue', 'price'=>'3') ) ), 1 => array( 'name' => 'sizes', 'options
array(
0 => array(
'name' => 'colors',
'options' => array(
array('name'=>'red', 'price'=>'2'),
array('name'=>'blue', 'price'=>'3')
)
),
1 => array(
'name' => 'sizes',
'options' => array(
array('name'=>'small', 'price'=>'5'),
array('name'=>'large', 'price'=>'10')
)
),
);
array(
'red' => '2',
'blue' => '3',
'small' => '5',
'large' => '10'
);
我想将所有嵌套选项数组的名称/价格合并为一个,因此如下所示:
array(
0 => array(
'name' => 'colors',
'options' => array(
array('name'=>'red', 'price'=>'2'),
array('name'=>'blue', 'price'=>'3')
)
),
1 => array(
'name' => 'sizes',
'options' => array(
array('name'=>'small', 'price'=>'5'),
array('name'=>'large', 'price'=>'10')
)
),
);
array(
'red' => '2',
'blue' => '3',
'small' => '5',
'large' => '10'
);
我觉得这很简单,但我尝试的任何东西都太复杂了。任何帮助都将不胜感激
…是的,不久前我刚刚发布了几乎相同的问题。这有点不同,我首先想问的是-哦,对不起。我不确定是否可以通过内部方法来实现,例如
array\u merge()
,array\u combine()
,等等,因为您的结构似乎非常特殊。但是迭代数组并自己构建一个新数组怎么样
function customRearrange($arr) {
$result = array();
foreach ($arr as $group) {
foreach ($group['options'] as $option) {
// prevents values from being overwritten, uncomment if unwanted
if (!array_key_exists($option['name'], $result))
$result[ $option['name'] ] = $option['price'];
}
}
return $result;
}
你需要决定你将如何处理碰撞,无论如何,这里同样会给你正确的方向:
$newArray = array();
foreach ($array as $i => $item)
foreach ($item['options'] as $j => $option)
$newArray[$option['name']] = $option['price'];
另一种方法是,假设数组已分配给变量
$a
:
<?php
for ($i = 0; $i < count($a); $i++) {
$key = $a[$i]['name'];
$options = $a[$i]['options'];
for ($j = 0; $j < count($options); $j++) {
$optkey = $options[$j]['name'];
$prices[$optkey] = $options[$j]['price'];
}
}
print_r($prices);
迭代嵌套数组中的“选项”并创建新数组:
<?php
$arr = array(
0 => array(
'name' => 'colors',
'options' => array(
array('name'=>'red', 'price'=>'2'),
array('name'=>'blue', 'price'=>'3')
)
),
1 => array(
'name' => 'sizes',
'options' => array(
array('name'=>'small', 'price'=>'5'),
array('name'=>'large', 'price'=>'10')
)
),
);
$group = array();
foreach($arr as $a){
foreach($a['options'] as $op){
$group[$op['name']] = $op['price'];
}
}
print_r($group);
?>