重新索引数组值

我想在 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"},}

}


梦里花落0921
浏览 121回答 1
1回答

繁星点点滴滴

首先,您可以将值转换为数组,因为输入是 json。然后解析数组,删除所需的值。解析数组后,您可以将其转换回 json(如果需要)。下一个脚本删除$valueToRemove变量中指示的值。<?php$jsonValues = '{"sequence": 2,"data": {&nbsp; &nbsp; "1": {"sequence": "1", "todo": "dummy todo"},&nbsp; &nbsp; "2": {"sequence": "2", "todo": "dummy todo 2"},&nbsp; &nbsp; "3": {"sequence": "3", "todo": "ssdummy tossssdo 3"}&nbsp; &nbsp; }}';$valueToRemove = 2;$arrayValues = json_decode($jsonValues, true);$oldData = $arrayValues['data'];$newData = array();$counter = 0;foreach ($oldData as $oldIndex => $oldValue) {&nbsp; &nbsp; if ($valueToRemove != $oldIndex) {&nbsp; &nbsp; &nbsp; &nbsp; $counter++;&nbsp; &nbsp; &nbsp; &nbsp; $newData[$counter] = array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'sequence' => $counter,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'todo' => $oldValue['todo']&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; }}$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"}}}
打开App,查看更多内容
随时随地看视频慕课网APP