0

I need help to change the index of an array.

I have this array:

$items = array('items' => array(
    0 => array(
        'item_id' => 1,
        'item_amount' => 100,
    ),
    1 => array(), 
));

Now I want to remove the index, based on the value of item_id, but I don't know how to do this.

I've tried to do it as follows, but doesn't work.

foreach($items['items'] as $key) {
  $removeIndex = $key['item_id'] == 1;
  if($removeIndex) {
     unset($removeIndex);
  }  
}

How can I do this?

trincot
  • 317,000
  • 35
  • 244
  • 286

3 Answers3

3

You need to use unset like this:

foreach($items['items'] as $index => $key) { // also get the index!
  if (!isset($key['item_id'])) continue; // skip
  $removeIndex = $key['item_id'] == 1;
  if($removeIndex) {
     unset($items['items'][$index]['item_id']); // specify path to that entry
  }  
}

See it run on eval.in.

To unset something in your nested array structure, you need to act on that array itself. unset($removeIndex) does not change the array, because that is a boolean value.

The extra if is there for the case when you don't have an item_id in some sub-array: in that case that iteration of the loop is skipped.

Removing the entire "row"

If your aim is to also remove the sub-array to which the item_id belongs (so including the item_amount and any other value in that sub-array), then just shorten the "path" in the unset statement:

foreach($items['items'] as $index => $key) { // also get the index!
  if (!isset($key['item_id'])) continue; // skip
  $removeIndex = $key['item_id'] == 1;
  if($removeIndex) {
     unset($items['items'][$index]); // specify path to that entry
  }  
}

See it run on eval.in.

trincot
  • 317,000
  • 35
  • 244
  • 286
0

If you want to remove the specific entry 'item_id' in the $items array, you have to refer to it and use both keys, like in:

foreach($items['items'] as $key => $val) {
  if (!isset($val['item_id'])) continue;
  $removeIndex = $val['item_id'] == 1;
  if($removeIndex)
     unset($items['items'][$key]);
}

If you downvote, please state why you think this answer is not appropriate.

syck
  • 2,984
  • 1
  • 13
  • 23
  • Nope, that was intentionally, but in the end it is still unclear what the OP wants to get. It is only so hard to find that out via comments. :-) – syck Jul 16 '16 at 16:44
0

You need to call unset($items['items'][0]). For your case it will be something like this:

$id = 1;
$keyToRemove = false;

foreach ($items['items'] as $key => $value) {
  if ($value['item_id'] == $id) {
    $keyToRemove = $key;
    break;
  };
}

if ($keyToRemove) {
  unset($items['items'][$keyToRemove]);
}
oakymax
  • 1,454
  • 1
  • 14
  • 21