-2

I want to reindex my array both key and values in PHP, example if delete data: "2" , data 3 will be reindex to 2 and values inside of array 3 {sequence : 3 "ssdummy tossssdo 3"} will be change to {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"},}
}
  • 1
    This has already been answered here I believe: https://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php – pendo May 10 '19 at 02:03
  • Possible duplicate of [How do you reindex an array in PHP?](https://stackoverflow.com/questions/591094/how-do-you-reindex-an-array-in-php) –  May 10 '19 at 06:47
  • 1
    What advantage are you gaining by storing redundant data in the keys and the sequence values. (That's rhetorical.) First, you should tell us how you are using this data, so that we can tell you how to design your data structure. Right now, you are requiring an unnecessary volume of processing for no sensible reason. And where is you coding attempt? – mickmackusa May 10 '19 at 09:52

1 Answers1

0

First, you can convert your values to a array, as the input is a json. Then parse the array, to remove the required value. After parsing the array, you can convert it back to json (if it is needed). The next script remove the value indicated in the $valueToRemove variable.

<?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);
?>

I have the following output from the script:

{"sequence":2,"data":{"1":{"sequence":1,"todo":"dummy todo"},"2":{"sequence":2,"todo":"ssdummy tossssdo 3"}}}
Cosmin Staicu
  • 1,809
  • 2
  • 20
  • 27