Reputation: 709
I have an array of 50000 arrays and i want to remove the "id" key-value pair from each of them.
I would rather not loop through 50k elements and was wondering if there was an efficient way to do it.
Array
(
[0] => Array
(
[id] => 713061
[market] => usd-btc
[price] => 3893.69
)
[1] => Array
(
[id] => 713056
[market] => usd-btc
[price] => 3893.69
)
[2] => Array
(
[id] => 713051
[market] => usd-btc
[price] => 3893.69
)
[3] => Array
(
[id] => 713046
[market] => usd-btc
[price] => 3893.69
)
[4] => Array
(
[id] => 713041
[market] => usd-btc
[price] => 3892.95
)
[5] => Array
(
[id] => 713036
[market] => usd-btc
[price] => 3892.95
)
I tried both the following but does not seem to be working:
// Remove ID
foreach($server_data as $sd)
{
unset($sd['id']);
}
unset($server_data['id']);
PRINT_R($server_data);
The $server_data is still returning the array with the $id element;
Any thoughts?
Upvotes: 0
Views: 1125
Reputation: 53543
This creates a copy of the subarray, so when you change it, the main array is not affected:
foreach ($server_data as $sd)
{
unset($sd['id']);
}
You can unset from the original array:
foreach (array_keys($server_data) as $index)
{
unset($server_data[$index]['id']);
}
Or pass the subarray a reference so that the original is changed:
foreach ($server_data as &$sd)
{
unset($sd['id']);
}
Or, more tersely:
array_walk($server_data, function (&$item) { unset($item['id']); });
Upvotes: 3
Reputation: 78994
There's no reason I can think of to remove it (just ignore it), however you can run it through a callback that removes id
and returns the rest:
$server_data = array_map(function($v) { unset($v['id']); return $v; }, $server_data);
Upvotes: 1