我希望我不是在这里重新发布或者是多余的,还在浏览php数组。我有一个多维数组,如下所示:
Array
(
[0] => stdClass Object
(
[field_name] => step_one
[field_value] => A Message
)
[1] => stdClass Object
(
[field_name] => message_color
[field_value] =>
)
[2] => stdClass Object
(
[field_name] => Submitted Login
[field_value] => admin
)
[3] => stdClass Object
(
[field_name] => Submitted From
[field_value] => 127.0.0.1
)
[4] => stdClass Object
(
[field_name] => step_one
[field_value] => Another Message
)
[5] => stdClass Object
(
[field_name] => message_color
[field_value] => orange
)
[6] => stdClass Object
(
[field_name] => Submitted Login
[field_value] => admin
)
[7] => stdClass Object
(
[field_name] => Submitted From
[field_value] => 127.0.0.1
)
[8] => stdClass Object
(
[field_name] => step_one
[field_value] => some Other Idea
)
[9] => stdClass Object
(
[field_name] => message_color
[field_value] => pink
)
[10] => stdClass Object
(
[field_name] => Submitted Login
[field_value] => admin
)
[11] => stdClass Object
(
[field_name] => Submitted From
[field_value] => 127.0.0.1
)
) 我希望它读起来像这样:
Array(
Array [0] (
[step_one] => Message
[message_color] =>
)
Array [1] (
[step_one] => Another Message
[message_color] => orange
)
Array [2] (
[step_one] => some other idea
[message_color] => pink
)
但我不知道如何在php中实现目标。我已经尝试过array_merge()和array_combine(),但我只是没有到达任何地方。任何帮助将不胜感激!
答案 0 :(得分:2)
这是一个简单的循环。
foreach($obj_array as $obj){
$a_array[$obj->field_name]=$obj->field_value;
}
答案 1 :(得分:1)
Tim Withers解决方案或......
function gather($arr){
return array($arr->field_name=>$arr->field_value);
}
$newArr = array_map('gather',$oldArr);
oldArr是原作!
答案 2 :(得分:0)
$reduce = function($input)
{
$current = 0;
return array_reduce($input, function($a, $b) use (&$current) {
isset($a[$current][$b->field_name]) && $current++;
$a[$current][$b->field_name] = $b->field_value;
return $a;
}, array());
};
print_r($reduce($input));
输出(我有一个较小的数据集):
Array
(
[0] => Array
(
[step_one] => A Message
[message_color] =>
)
[1] => Array
(
[step_one] => Another Message
)
)
如果在当前索引($current
)中密钥已经存在,则调整是启动一个新元素。