kate_hudson kate_hudson - 1 year ago 139
PHP Question

Unsetting element in array

I am trying to remove a key/value pair from an array but it does not seem to work. Basically, I make an API call which returns JSON. As such I do

$tempArray = json_decode($projects, true);

If I output $tempArray I see something like this

array:2 [
0 => array:9 [
"id" => 4
"name" => "Some Project Name"
"value" => "234"
"user_id" => "1"
"client_id" => "97"
"contact" => "Jane Berry"
1 => array:9 [
"id" => 3
"name" => "Another Project Name"
"value" => "6"
"user_id" => "1"
"client_id" => "97"
"contact" => "John Doe"

I essentially need to remove the value element so I do this


If I output $tempArray after the unset, it displays exactly the same as before, with the value element and value there.

What do I need to do to completely remove this from my array?


Answer Source

unset will not look recursivly to sub-array to remove the key value. Only if you have at first level a key named value will be removed. In your array first level keys are: 0 and 1. So to remove value from all sub-arrays you have to go throw all items from the array and unset it. You can do this with a simple foreach.

foreach($tempArray as $key => $data) { 
   $tempArray[$key] = $data; //Overwrite old data with new with value unset.

Now you will not have value key in sub-array items.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download