0

This is my array and I want to add some elements to make it like 2nd array

1.)

array(7) {
  [0] => array(3) {
    ["name"] => string(9) "airG Chat"
    ["product_id"] => int(2469)
    ["price"] => string(4) "0.00"
  }

  [1] => array(3) {
    ["name"] => string(9) "PingChat!"
    ["product_id"] => int(7620)
    ["price"] => string(4) "0.00"
  }
  [2] => array(3) {
    ["name"] => string(25) "MobiEXPLORE Zagreb County"
    ["product_id"] => int(8455)
    ["price"] => string(4) "0.00"
  }
}

After adding items, it should be like this, I tried using for each function but did not work. 2.)

array(7) {
  [0] => array(3) {
    ["name"] => string(9) "airG Chat"
    ["product_id"] => int(2469)
    ["price"] => string(4) "0.00"
    ["description"] => string(23) "this is the custom test"
    ["brief_description"] => string(23) "this is the custom test"
  }

  [1] => array(3) {
    ["name"] => string(9) "PingChat!"
    ["product_id"] => int(7620)
    ["price"] => string(4) "0.00"
    ["description"] => string(23) "this is the custom test"
    ["brief_description"] => string(23) "this is the custom test"
  }
  [2] => array(3) {
    ["name"] => string(25) "MobiEXPLORE Zagreb County"
    ["product_id"] => int(8455)
    ["price"] => string(4) "0.00"
    ["description"] => string(23) "this is the custom test"
    ["brief_description"] => string(23) "this is the custom test"
  }
}
Shaolin
  • 2,541
  • 4
  • 30
  • 41

2 Answers2

3

Use foreach with reference (&):

foreach($data as &$datum) {
    $datum["description"] = "this is the custom test";
    $datum["brief_description"] = "this is the custom test";
}

If you'd prefer not to use & (to avoid this problem), you can do

foreach($data as $i => $datum) {
    $data[$i]["description"] = "this is the custom test";
    $data[$i]["brief_description"] = "this is the custom test";
}
Community
  • 1
  • 1
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
2

If you use foreach and want to change the original array, you need to add &.

foreach ($arr as &$item) {
  $item["description"] = "this is the custom test";
  $item["brief_description"] = "this is the custom test";
}
xdazz
  • 158,678
  • 38
  • 247
  • 274