从数组中删除字符串项
问题描述:
我有一个数组,字符串和数组具有相同的名称“item”,一个实例是一个数组,另一个是数组中的字符串,我想删除整个“item”来自阵列的字符串从数组中删除字符串项
该阵列;
//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
)
)
))
有什么建议吗?
答
你必须知道如何阵列的工作,这个多维数组您可以通过删除删除:数组[0] [0],数组[0] [1]
unset($a[0][0]);
unset($a[0][1]);
答
你可能有两个嵌套做地图如下;
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))
答
你可以使用一个递归PHP函数像这样的:
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);
}
这样称呼它:
removeItems($arr);
看到它在eval.in运行。
输出是:
Array
(
[0] => Array
(
[id] => 109
[text] => dashboard
[items] => Array
(
[0] => Array
(
[id] => 1
[text] => financial_dashboard
)
[1] => Array
(
[id] => 108
[text] => project_dashboard
)
)
)
)
这是一个JSON,对不对? –
你必须知道数组是如何工作的,这个多维数组可以通过删除来删除:array [0] [0],array [0] [1] – mohade
'for(i = 0; i
jonzee