John Davidson

php - How to remove any sub array and keep only two top levels of a multidimensional array?

0 comments
Message:


I need to modify an array with subarrays and keep only the top two arrays (array -> results - x) and remove any subarray below. For example array "location" & "syncState" should be removed.


Original array:


$device_array = [
"totalCount" => "3",
"results" => [
[
"id" => "2",
"serialNumber" => "DX",
"location" => ["id" => "5", "locationName" => "US"]
],
[
"id" => "4",
"serialNumber" => "DM",
"syncState" => ["id" => "7", "locationName" => "DE"]
],
[
"id" => "5",
"serialNumber" => "C0"
]
]
];

The array should look like this:


Array
(
[totalCount] => 3
[results] => Array
(
[0] => Array
(
[id] => 2
[serialNumber] => DX
)
[1] => Array
(
[id] => 4
[serialNumber] => DM
)
[2] => Array
(
[id] => 5
[serialNumber] => C0
)
)
)

I'm trying to loop through the arrays (sub arrays included) but I can't remove all of the subarrays that sit under $device_array['results'][x].


foreach ($device_array as $key => $value) {
if(is_array($value)) {
unset($device_array['results'][0]['location']);
}
}


My Answer:
You can achieve this by using a combination of array_map and array_slice functions. Here's how you can do it:

php
$device_array['results'] = array_map(function($result) {
return array_slice($result, 0, 2);
}, $device_array['results']);

print_r($device_array);


This code will loop through each subarray in the 'results' array and keep only the first two elements, effectively removing any subarrays below them.

Rate this post

5 of 5 based on 8959 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us