1

I have this output:

enter image description here

I don't have any idea how can I make my array look like this:

$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
    ]


]

I have started the loop but I don't really know how to get that kind of structure.

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

        }
    }
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Rbex
  • 1,519
  • 6
  • 24
  • 50

3 Answers3

3

You can iterate the outer and inner arrays to build your data like so, this allows you to add further keys to the array later - but does depend on your inner array keys being contiguous

$wishlist = [];
foreach ($array as $outerKey => $outerValue) {
    foreach ($outerValue as $innerKey => $innerValue) {
        $wishlist[$innerKey][$outerKey] = $innerValue;
    }
}
danjam
  • 1,064
  • 9
  • 13
1

Your loop should look like this:

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

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

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

        }
    }
moni_dragu
  • 1,163
  • 9
  • 16
0

You should have to use for loop.

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];
}

or user foreach like this

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];
}
Keyur Mistry
  • 926
  • 6
  • 18