我有一个如下所示的数组:
Array
(
[0] => Array
(
[name] => color
[value] => red
)
[1] => Array
(
[name] => shape
[value] => square
)
[2] => Array
(
[name] => price
[value] => $15
)
)
我希望得到这样的结果:
$myArr = array (
'color' => 'red',
'shape' => 'square',
'price' => '$15'
)
我试图循环但无法让它工作。
foreach($myArr as $id => $values){
foreach ($values as $key => $value) {
if($key == 'name') {
//add to array key
} else {
//add to that array key value
}
}
}
希望你们能帮我解决问题。
答案 0 :(得分:2)
您可以使用array_column
和array_combine
$arr = array(
array("name" => 'color',"value" => 'red'),
array("name" => 'shape',"value" => 'square'),
array("name" => 'price',"value" => '$15')
);
$newArr = array_combine(array_column($arr,'name'),array_column($arr,'value'));
echo "<pre>";
print_r( $newArr );
echo "</pre>";
这将导致:
Array
(
[color] => red
[shape] => square
[price] => $15
)
答案 1 :(得分:1)
$a = [
0 => [
"name" => "color",
"value" => "red",
],
1 => [
"name" => "shape",
"value" => "square",
],
2 => [
"name" => "price",
"value" => "$15",
]
];
$b = [];
foreach($a as $v)
{
$b[$v["name"]] = $v["value"];
}
var_dump($b);
结果
array(3) {
["color"]=>
string(3) "red"
["shape"]=>
string(6) "square"
["price"]=>
string(3) "$15"
}
答案 2 :(得分:0)
$arr = array
(
0 => array
(
'name' => 'color',
'value' => 'red'
),
1 => array
(
'name' => 'shape',
'value' => 'square'
),
2 => array
(
'name' => 'price',
'value' => '$15'
)
);
$final_array =[];
foreach($arr as $key=> $val){
$final_array[$val['name']] = $val['value'];
}
echo "<pre>"; print_r($final_array);