PHP循环多维关联数组

时间:2016-10-17 07:03:02

标签: php arrays multidimensional-array

我有这个输出:

enter image description here

我不知道如何让我的数组看起来像这样:

$array[

    0 => [
        'item_id' => 6,
        'price' => "2311.00",
        'qty' => 12,
        'discount' => 0
    ],

    1 => [
        'item_id' => 7,
        'price' => "1231.00",
        'qty' => 1,
        'discount' => 12
    ],

    2 => [
        'item_id' => 8,
        'price' => "123896.00",
        'qty' => 0,
        'discount' => 24
    ]


]

我已经开始了循环,但我真的不知道如何获得这种结构。

    foreach( $array  as $wishlist ){
        foreach( $wishlist as $k => $v ){

        }
    }

3 个答案:

答案 0 :(得分:3)

你可以迭代外部和内部数组来构建你的数据,这样你就可以在以后向数组中添加更多的键 - 但这取决于你的内部数组键是连续的

$wishlist = [];
foreach ($array as $outerKey => $outerValue) {
    foreach ($outerValue as $innerKey => $innerValue) {
        $wishlist[$innerKey][$outerKey] = $innerValue;
    }
}

答案 1 :(得分:1)

你的循环应如下所示:

 foreach( $array as $item => $wishlist ){

       foreach( $wishlist as $k => $v ){

          $new_array[$k][$item] = $v;

        }
    }

答案 2 :(得分:0)

你应该使用for循环。

for($i=0;$i<count(youarray['item_id']);$i++) {
  $wishlist[$i]['item_id'] = youarray['item_id'][$i];
  $wishlist[$i]['price'] = youarray['price'][$i];
  $wishlist[$i]['qty'] = youarray['qty'][$i];
  $wishlist[$i]['discount'] = youarray['discount'][$i];
}

或像这样的用户foreach

foreach(youarray['item_id'] as $key=>$val) {
  $wishlist[$key]['item_id'] = $val;
  $wishlist[$key]['price'] = youarray['price'][$key];
  $wishlist[$key]['qty'] = youarray['qty'][$key];
  $wishlist[$key]['discount'] = youarray['discount'][$key];
}