0

我想重组我的数组,使其在 json 中看起来更好这是我当前变量的 print_r:

Array
(
    [0] => Array
        (
            [item_id] => 2
        )

    [1] => Array
        (
            [item_id] => 1
        )

    [2] => Array
        (
            [item_id] => 1
        )
)

我想重建它是这样或类似的:

编辑

Array
(
    [item_id] = array([0]=>'2',[1]=>'1', [2]=>'1');
)

对不起我糟糕的英语 m(_ _)m 我只希望 item_id 有多个值。

4

3 回答 3

1

The hurdle

You actually can't in any way produce the output that you desire, since the key needs to be unique.

You can't use a key of item_id more than once, every time you try and set it, it will override what was in there last.

Think about it, how do you then look up the item with key of item_id, you can't, because three things would have that same key.

If the only reason is for cosmetics, I'd leave the output as you currently have it, although it may look a little messy in your JSON, it works.

A different approach

The best you can hope, is to get an output of:

'item_id' => array(
    2,
    1,
    1
)

You can do this with the help of the array_map function:

$array = array('item_id' => array_map('current', $array));
于 2013-04-22T04:41:30.463 回答
0

这可以使用此代码来完成。

$a['item_id'] = array();
foreach($arr as $key=>$val) {
     $a['item_id'][] = $val['item_id'];
}
print_r($a);
于 2013-04-22T04:33:37.013 回答
0
$array = array('item_id' => array_map('current', $array));
于 2013-04-22T04:38:46.410 回答