我想在php中重新索引键和值的数组
例如,如果删除数据:“ 2”,则数据3将被重新索引为2,而array 3 {sequence : 3 "ssdummy tossssdo 3"}
内部的值将被更改为{sequence : 2 "ssdummy tossssdo 3"}
{
"sequence": 2,
"data": {
"1": {"sequence": "1", "todo": "dummy todo"},
"2": {"sequence": "2", "todo": "dummy todo 2"},
"3": {"sequence": "3", "todo": "ssdummy tossssdo 3"},}
}
答案 0 :(得分:0)
首先,您可以将值转换为数组,因为输入是json。然后解析该数组,以删除所需的值。
解析数组后,可以将其转换回json(如果需要)。
下一个脚本将删除$valueToRemove
变量中指示的值。
<?php
$jsonValues = '{
"sequence": 2,
"data": {
"1": {"sequence": "1", "todo": "dummy todo"},
"2": {"sequence": "2", "todo": "dummy todo 2"},
"3": {"sequence": "3", "todo": "ssdummy tossssdo 3"}
}
}';
$valueToRemove = 2;
$arrayValues = json_decode($jsonValues, true);
$oldData = $arrayValues['data'];
$newData = array();
$counter = 0;
foreach ($oldData as $oldIndex => $oldValue) {
if ($valueToRemove != $oldIndex) {
$counter++;
$newData[$counter] = array(
'sequence' => $counter,
'todo' => $oldValue['todo']
);
}
}
$arrayValues['data'] = $newData;
$jsonValues = json_encode($arrayValues);
var_dump($jsonValues);
?>
我从脚本中得到以下输出:
{"sequence":2,"data":{"1":{"sequence":1,"todo":"dummy todo"},"2":{"sequence":2,"todo":"ssdummy tossssdo 3"}}}