2

I have structure of an array like this :

[{"name":"username1","id":0},{"name":"username2","id":1}]

in my mysql database it is json encoded i am trying to search for a specific id and delete that object and save other array as it is.

$arr_data=json_decode($jsonData);
         foreach(arr_data as $k=> $data)
            {
             if($request->id==$data->id)
                {
                  unset($arr_data[$k]);
                  $updateData =  DataTable::where(['id'=>$request->id])
                    ->update(['update_column' =>json_encode($arr_data)]);
                }
            }

Issue is my data is not stored in proper format after deleting.

New json formatted data is store in this format :

{"1":{"name":"username1","id":1}}

Any suggestion to solve this issue.

3
  • @LelioFaieta: In my above code index gets removed but i have to save remaining array element that format is not saved properly Commented Nov 3, 2020 at 14:08
  • This answer: stackoverflow.com/a/20373067/14481105 shows you how to remove keys from your new data. Commented Nov 3, 2020 at 14:58
  • json_encode() keeps your array keys, unless it considers they can be omitted: "When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair. " Commented Nov 3, 2020 at 16:27

1 Answer 1

0

This works for me

$jsonData = '[{"name":"username1","id":0},{"name":"username2","id":1},{"name":"username2","id":2}]';

$arr_data=json_decode($jsonData);

if(($index = array_search($request->id, array_column( $arr_data, 'id'))) !== false) {
  unset($arr_data[$index]);
  $arr_data = array_values($arr_data);
}

$updateData =  DataTable::where(['id'=>$request->id])
                ->update(['update_column' =>json_encode($arr_data)]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.