0

I've a sample json data

{
   "cities": {
          "total": 100,
          "count":5000,
          "cities_list" : [{
                 "name": "city1",
                 "count": 1000
          },
           {
                 "name": "city2",
                 "count": 2000
           }
          ]
   }


}

How can I append the cities_list array directly to cities which would look like

{
     "cities": [{
           "name": "city1",
           "count": 1000
      },
      {
           "name": "city2",
           "count": 2000 
      }
     ]
}
2
  • Can you share PHP code? Like how are you getting the data and what variables do you store them in? Commented Aug 13, 2021 at 17:56
  • Unfortunately, this is a piece where I got stuck on. As I dont have much knowledge on Json, I posted here. basically, this is a response coming from repository function with mysql db. Commented Aug 13, 2021 at 18:03

3 Answers 3

1

Not sure, about all the stuff, but i assume your "json" or just associative array is in variable (for example foo)

Now you should set:

$foo["cities"] = $foo["citites"]["citites_list"];
Sign up to request clarification or add additional context in comments.

Comments

0

Let's say that your JSON result is stored in a variable called $results

$results = json_decode($results,true); //convert json to array
    
$modifiedArray= [];

$modifiedArray= $results['cities']['cities_list']->map(function ($item, $key) {
    return ['cities'][][
        'name' => $item->name,
        'count' => $item->count
    ];
});

This is more of a laravel approach since you also tagged laravel. Your modified array is an array type if you want to be a JSON again you have to encode it into a JSON.

Comments

0

You can use the Unset function

$data= json_decode($your_json);
$json_arr = json_decode($your_json, true);   

unset($data->total);
unset($json_arr['total']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.