ubik
ubik

Reputation: 125

Remove/unset every other key in multidimensional array but preserve keys

I have a long multidimensional array with timestamps as keys which contain arrays of values. Something like this but with more timestamps:

array(3) {
  [1502609400]=>
  array(2) {
    ["Item1"]=>
    array(1) {
      ["PRICE"]=>
      float(100)
    }
    ["Item2"]=>
    array(1) {
      ["PRICE"]=>
      float(50)
    }
  }
  [1502611200]=>
  array(2) {
    ["Item1"]=>
    array(1) {
      ["PRICE"]=>
      float(200)
    }
    ["Item2"]=>
    array(1) {
      ["PRICE"]=>
      float(150)
    }
  }
  [1502613000]=>
  array(2) {
    ["Item1"]=>
    array(1) {
      ["PRICE"]=>
      float(500)
    }
    ["Item2"]=>
    array(1) {
      ["PRICE"]=>
      float(250)
    }
  }

How can I remove every every second array of the array without losing the keys as timestamp? So I end up with this:

array(3) {
  [1502609400]=>
  array(2) {
    ["Item1"]=>
    array(1) {
      ["PRICE"]=>
      float(100)
    }
    ["Item2"]=>
    array(1) {
      ["PRICE"]=>
      float(50)
    }
  }
  [1502613000]=>
  array(2) {
    ["Item1"]=>
    array(1) {
      ["PRICE"]=>
      float(500)
    }
    ["Item2"]=>
    array(1) {
      ["PRICE"]=>
      float(250)
    }
  }

If I use a for loop and unset every second key I lose all the keys and end up with 0, 1, 2 etc. instead of the timestamp.

Upvotes: 0

Views: 700

Answers (3)

M_Idrees
M_Idrees

Reputation: 2172

In a loop, check for index and unset every second element:

You can use custom $index variable, like this:

$index = 0; // points to first element

foreach ($array as $key => $value) {
    if ($index % 2 != 0) { //check for un-even
        unset($array[$key]);
    }   

    $index++; // move pointer to next element
}

Upvotes: 4

Sarkouille
Sarkouille

Reputation: 1232

In that kind of case, a simple foreach can be more efficient perfwise than a standard function :

foreach ($array as $key => $val) {
    if (array_key_exists('Item2', $val)) {
        unset($val['Item2']);
    }
}

Upvotes: 1

Osama
Osama

Reputation: 3040

$i=1 // where the key to remove 
$x=0; //loop to determine the key position
foreach ($array as $key=>$value){
if($x==$i){
unset($array[$key]);
}
$x++;
}

Upvotes: 1

Related Questions