1

我希望我不会在这里重新发布或多余,仍然在摸索 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(),但我只是没有得到任何结果。任何帮助将不胜感激!

4

3 回答 3

2

这是一个简单的循环可以做到这一点。

foreach($obj_array as $obj){
    $a_array[$obj->field_name]=$obj->field_value;
}
于 2012-09-18T00:26:38.393 回答
1

蒂姆威瑟斯解决方案或...

function gather($arr){
  return array($arr->field_name=>$arr->field_value);
}

$newArr = array_map('gather',$oldArr);

oldArr 是原始的!

于 2012-09-18T00:34:53.960 回答
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如果当前索引 ( ) 中的键已经存在,则调整是开始一个新元素。

于 2012-09-18T01:47:11.420 回答