I have an array, the string and the array have same names "item", one instance is an array and the other is a string in the array, I would like to remove the entire "item" string from the array
The array;
//JSON
[{
"id":"109",
"text":"dashboard",
"items":[ //to be ignored
{
"id":"1",
"text":"financial_dashboard",
"items":"109" //to be deleted
},
{
"id":"108",
"text":"project_dashboard",
"items":"109" //to be deleted
}
]
}]
//Array PHP
(
[0] => Array
(
[id] => 109
[expanded] => true
[text] => Dashboard
[items] => Array //to be ignored
(
[0] => Array
(
[id] => 1
[expanded] => true
[text] => Financial Dashboard
[items] => 109 //to be deleted
)
[1] => Array
(
[id] => 108
[expanded] => true
[text] => Project Dashboard
[items] => 109 //to be deleted
)
)
))
Any suggestions?
you must know how the array work, this multidimensional array you can delete this by delete : array[0][0] and array[0][1]
unset($a[0][0]);
unset($a[0][1]);
You might do with two nested maps as follows;
var arr = [{
"id":"109",
"text":"dashboard",
"items":[ //to be ignored
{
"id":"1",
"text":"financial_dashboard",
"items":"109" //to be deleted
},
{
"id":"108",
"text":"project_dashboard",
"items":"109" //to be deleted
}
]
}];
function delNestedItems(a){
return a.map(o => (o.items.map(q => (delete q.items,q)),o));
}
console.log(delNestedItems(arr))
</div>
You could use a recursive PHP function like this one:
function removeItems(&$arr) {
if (!is_array($arr)) return;
if (isset($arr["items"]) && is_string($arr["items"])) unset($arr["items"]);
foreach ($arr as &$value ) removeItems($value);
}
Call it like this:
removeItems($arr);
See it run on eval.in.
Output is:
Array
(
[0] => Array
(
[id] => 109
[text] => dashboard
[items] => Array
(
[0] => Array
(
[id] => 1
[text] => financial_dashboard
)
[1] => Array
(
[id] => 108
[text] => project_dashboard
)
)
)
)