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
}
]
}
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"];
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.
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']);
Related
I'm working on WordPress site and been asked to supply mobile developer by JSON API data for a slider. I have to add the slider data like images and titles etc. I've found a plugin which serve an end point called MetaSlider. I've did required things and the response was perfect. but the developer replied by this:
"I am not talking about data. It should be a valid JSON array. Plz have a look at data structure of response object
"0": {
"id": 2669,
"title": "New Slideshow",
This is not valid json. It should be a JSON Array like this
[ {
"id": 2669,
"title": "New Slideshow","
Does any one have a clue?
I looked for a plugin that can do the job but I didn't find any.
I was experiencing the same issue.
If your array is as result of using array_map, wrap your response with array_values($data).
This is the function I have as a callback for register_rest_route;
public function terms_ep( $request ) {
$terms = get_terms('my_taxonomy', []);
$data = array_map(function($t){
return [
'id' => $t->term_id,
'name' => $t->name
];
}, $terms);
return rest_ensure_response( array_values($data) );
}
With array_values it produces a nice json array:
[
{
"id": 13,
"name": "A"
},
{
"id": 12,
"name": "B"
}
]
Without the response is this object response:
{
"0": {
"id": 13,
"name": "A"
},
"2": {
"id": 12,
"name": "B"
}
}
I have this JSON payload below and want to get names and ids from the payload. However, l cannot object names and ids from the payload.
Decode JSON
$result = json_decode($resp->getBody()->getContents(), true);
return response()->json(
[
"code" => 200,
"message" => "OK",
"payload"=> $result['payload'] ?? '',
]);
Api json payloads
{
"code": 200,
"message": "OK",
"payload": {
"items": [
{
"name": "Hostel",
"image": {
"name": "WEWEBBFC791FD50E347BD.jpeg"
},
"rate": {
"amount": "3.0000",
"currency": {
"code": "US"
}
},
"pricing": [
{
"rate": "3.0000"
}
],
"id": 12, // get this id
"created_at": "2021-02-28T11:08:25+00:00"
}
..........
],
"total": 10,
"offset": 10
}
}
Use json_decode to decode the json to an associative array, then access the elements of the array as you would any other assoc array.
It looks as though you can have one or more items in your collection, so you'll want to use a loop to iterate over them.
$decoded = json_decode($json, true);
foreach ($decoded['payload']['items'] as $item) {
$name = $items['name'];
$id = $items['id'];
dump($name, $id);
}
Let's say I have a Model which outputs 3 models that is this data:
[
{
"id": 1,
"data": [
{
"id": "coins",
"qty": 3
},
{
"id": "ruby",
"qty": 52
}
]
},
{
"id": 2,
"data": [
{
"id": "coins",
"qty": 140
}
]
},
{
"id": 3,
"data": [
{
"id": "coins",
"qty": 84
}
]
}
]
How would I, using Collections, sort this data by coins's qty and who has the most.
A nice clean way of doing this is with the "." operator.
$projects = Project::all()->load('tasks')->sortBy('data.qty');
Json is mainly used as a common format for sending data.
In Laravel you can convert a json object to a php array easily by using json_decode().
$phpArray = json_decode($json);
From here you can convert it to a collection to take advantage of laravels collection functions.
$laravelArray = collect($phpArray);
After this take a look at https://laravel.com/docs/5.8/collections to do sort/filter or do whatever you want to the array.
Or you can use pure php to solve this
$json is your json retrieved
$array = json_decode($json, true);
usort($array['data'], function($a, $b) {
return $a['qty'] <=> $b['qty'];
});
print_r($array);
See this example code
<?php
$json = '{
"Message": "Done.",
"Status": true,
"InnerData": [
{
"id": 66,
"name": "first",
"distance": 74
},
{
"id": 67,
"name": "second",
"distance": 153
},
{
"id": 68,
"name": "third",
"distance": 172
}
]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
return $a['distance'] <=> $b['distance'];
});
print_r($array);
I hope it's helps you.
Thanks.
try this
$array = collect($array)->sortBy('data.qty')->reverse()->toArray();
In PHP, I'd like to convert an array of objects like the following to a PHP array, using one of the properties as the associative array keys.
[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]
like this...
[
2 => "Suzy",
3 => "Joe",
4 => "Sara"
]
I can't use array_map because you can't set the keys from my understanding, but I'm wondering if there's a one-liner way to do it without a foreach loop.
To be clear, I want to maintain the keys in the output array, not puts the original keys inside the new array values like they do here: PHP's array_map including keys
It appears by "object" you mean a JSON object. Given that, you can use array_column() to pull out a single column from each row, and then array_combine() to use one column for the keys and another for the values:
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$out = array_combine(array_column($array, 'id'), array_column($array, 'name'));
print_r($out);
Yields:
Array
(
[2] => Suzy
[3] => Joe
[4] => Sara
)
2 liners and has a foreach though.
<?php
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$new_array = [];
foreach(json_decode($json,true) as $each_object) $new_array[$each_object['id']] = $each_object['name'];
print_r($new_array);
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$result = array_column($array, 'name', 'id');
I have an array which look like this :
Result 1:
{
"error_code": 0,
"error_message": "",
"return_data": {
"items": [
{
"id": 462,
"users": "1,36,38"
},
{
"id": 462,
"users": "1,4"
},...... //same for 20 result
]
}
}
I want the users to convert to an array,and separate by the comma,so the whole result will look like this :
The result I want:
{
"error_code": 0,
"error_message": "",
"return_data": {
"items": [
{
"id": 462,
"users": [
{
"user_id": 1
},
{
"user_id": 36
},
{
"user_id": 38
}
],
}.. //other result
]
}
}
Here is what I try :
$res = "array the get the Result 1";
$items = //"I get the items array"
foreach ($items as $key => $item) {
$usersArray = array(); //create a new Array
//spilt the string to array separate with ","
$usersIdArray = explode(',', $items['users']);
//assign the "user_id" key to each value
foreach ($userIdArray as $key => $user) {
$usersArray['user_id'] = $user;
}
//assign the result back to $res
$res['return_data']['items']['users'] = $usersArray;
}
After I assign the array to $res with this line of code $res['return_data']['items']['users'] = $usersArray; ,my result become like below,I state the problem inside the code :
{
"error_code": 0,
"error_message": "",
"return_data": {
"items": {
"0":{ <-- // here suddenly appear a number for each result
"id": 462,
"users": "1,36,38" //here nothing change (I want the array appear here)
},
"1":{
"id": 462,
"users": "1,36,38"
},
"2":{
"id": 462,
"users": "1,36,38"
},
"users": { //the array appear here but not the position I want..and it only appears 1 time.
"user_id": "38"
}
}
}
}
So my question is,how can I convert a String in an array to an array,assign value to the key,and make it inside the array?
Somebody please help..Thanks
Like the comments above, you could have done it the first time so you wouldn't need another structure conversion, but anyway, your code is already there a bit, its just you need to create another nesting since you want another level:
So you need another level here:
"users": [
{
"user_id": 1
},
{
"user_id": 36
},
{
"user_id": 38
}
],
So in the code, just add []. This translates into:
foreach ($items as $key => $item) {
$usersArray['id'] = $item['id'];
$usersArray['users'] = array(); //create a new Array
$usersIdArray = explode(',', $item['users']);
foreach ($usersIdArray as $key => $user) {
$usersArray['users'][] = array('user_id' => $user); // push each batch of key pair "user_id" key and value "each exploded id"
// another level ^
}
$res['return_data']['items'][] = $usersArray;
}
Here's the fiddle to check it out.