I have below JSON object, that is being posted from my frontend to my backend with Axios:
this.columns = JSON.parse(this.columns);
This can look like:
columns: {
1: {
position: "10"
},
2: {
position: "35"
},
3: {
position: "20"
}
}
Now, I need to sort this JSON object on my backend from lowest to highest position and then convert the JSON object to a string (because I am using the values in another command line input):
"{\"1\":{\"position\":\"10\"},\"2\":{\"position\":\"20\"},\"3\":{\"position\":\"35.00\"}}"
I am trying to sort this and then convert it to a string with PHP:
//Sort the columns
sort($this->columns);
$columns = json_encode($this->columns);
But this returns the columns as an array:
"[{"position":"10"},{"position":"20"},{"position":"35"}]"
How can I sort the JSON object, but return it as a string so I can use it on the command line?
I think This is What You Need
First Variant:
json_encode($this->columns, JSON_FORCE_OBJECT);
Second Variant
json_encode((object) $this->columns);
This gives you Json Object String
Example:
{"0":{"position":"10"},"1":{"position":"20"},"2":{"position":"35"}}
Consider Upvote if this answer helps you
You can json_decode with true flag and use array_multisort,
$temp = json_decode($temp['columns'], true);
array_multisort(array_column($temp['columns'], "position"), SORT_ASC, $temp['columns']);
echo json_encode($temp['columns']);
Demo.
Output:-
[{"position":"10"},{"position":"20"},{"position":"35"}]
Related
I have below json data and decode it to display on the screen. When I check the type of the value, it shows array instead of object. How to get actual type of value in PHP.
JSON is
{ "allData" : { "image" : [], "contents": {.., "box": {}, "text":[]} } }
When I decode and parse the above JSON data the "allData", "contents", "box" type are shows as array instead of object. How can I get those type as object and "image" type as array. Please help.
Thanks,
Guru
This normally occurs when you are using the true option in the json_decode function.
For eg.,
$str = '{"allData":{"image":["img1.png"],"contents":{"title":"title name","box":{"name":["sample text 1","sample text2"]},"text":[]}}}';
var_dump(json_decode($str, true));
Just try to remove the true in the json_decode function and you should get an object.
Hope this helps.
If you use json_decode with the true option, it will return the result as an array.
Maybe you can check this link.
If you get "Cannot use object of type stdClass as array" the error, you can look at this answer.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Extract from the RFC 7159 (JSON) :
These are the six structural characters:
begin-array = ws %x5B ws ; [ left square bracket
begin-object = ws %x7B ws ; { left curly bracket
end-array = ws %x5D ws ; ] right square bracket
end-object = ws %x7D ws ; } right curly bracket
..
However: php allows you to treat the result as an array (of arrays)
so:
json_decode($json, true); // return as array
returns the result as an array.
and
json_decode($json)
gives you the result as Objects AND arrays . So given your example:
"allData" : { "image" : [], ..
returns a stdClass-Object with the field "image" of type array. The array is empty for your example.
So to retrieve all images, use something like:
$result=json_decode($json);
foreach($result->allData->image as $img) {
echo "found image: $img.";
}
This is my json:
{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}
I want to remove the second level keys (e.g "26:" and "28":) using PHP.
In other words, I want to replace the double-quoted number keys with zero-indexed numeric keys.
How can I make it look like this:
{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}
Here is the demo.
Code:
// declare $json
$array=json_decode($json,true); // decode as array
// overwrite subarray with zero-indexed keys while preserving subarray values
$array['all_counts_reports']=array_values($array['all_counts_reports']);
var_export(json_encode($array)); // return to json
Input:
$json='{
"all_counts_reports":{
"26":{
"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
"28":{
"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
}
}';
Output:
'{"all_counts_reports":
[
{"name":"kumar",
"date":"2017-04-27",
"trips_per_day":"2",
"cash_trips":"0",
"credit_trips":"1",
"compliment_trips":"1"
},
{"name":"kumar",
"date":"2017-04-29",
"trips_per_day":"1",
"cash_trips":"1",
"credit_trips":"0",
"compliment_trips":"0"
}
]
}'
In your javascript, use JSON.parse() to strip the wrapping single quotes:
var str='{"all_counts_reports":[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]}';
var json=JSON.parse(str);
console.log(json);
And because we are running with assumptions, if you want to remove the all_counts_reports key as well, you can use this one-liner:
Code:
$new_json=json_encode(array_values(current(json_decode($json,true))));
Output:
'[{"name":"kumar","date":"2017-04-27","trips_per_day":"2","cash_trips":"0","credit_trips":"1","compliment_trips":"1"},{"name":"kumar","date":"2017-04-29","trips_per_day":"1","cash_trips":"1","credit_trips":"0","compliment_trips":"0"}]'
$array = json_decode($your_json_string,true);
print_r($array);
$result = array();
foreach($array['all_counts_reports'] as $rep){
$result['all_counts_reports'][] = array(
"name"=>$rep['name'],
"date"=>$rep['date'],
"trips_per_day"=>$rep['trips_per_day'],
"cash_trips"=>$rep['cash_trips'],
"credit_trips"=>$rep['credit_trips'],
"compliment_trips"=>$rep['compliment_trips'],
);
}
$result_json = json_encode($result);
echo $result_json;
There may be better solution, but this one is right now in my mind
Its unclear that what you looking for, if you just want to remove and dont want to maintain as original json then you can do like this example. But if you dont want your all_counts_reports treated as array [] then this example will not help.
And simply pass to android then above will work.
I tried this code
$jsonlogcontents='{"buildings":"townhall","Army":{ "Paladins":{ "325648":0, "546545":4 }, "Knights":{ "325648":-2, "546545":0 } } }';
$phpArray = json_decode($jsonlogcontents, false);
echo $phpArray->buildings;
echo $phpArray->Army;
This is just a sample of my code, the JSON file is too large to include and has sensitive information. The problem I'm having is I can't get the value or print the value of
$phpArray->Army
It give's me an error. I can however print or get the value of
$phpArray->buildings
I'm thinking that when you decode a JSON file/contents in PHP, you can't get/print/store the value of a 'key' that has more set of info (more { and }) or brackets in it. You can only print/get values for keys who's value's contain only 1 value and nothing else.
If this is the case, what can I do to get the contents of the key that has more JSON codes in it. Also, how can I convert the contents of a key that has more JSON info in it into a string? the conversion is so I can display the value of that key to the page or echo it
The error is because Army is an object, and echo doesn't know how to convert it to a string for display. Use:
print_r($phpArray->Army);
or:
var_dump($phpArray->Army);
to see its contents.
P.S. $phpArray not an array but an object.
For Army however, I will need to do another json_decode() for that.
You don't. json_decode() decodes the entire structure in one call, into one large object (or array). No matter how deeply nested the data is, you call json_decode() once and you're done. That's why Army is not a JSON string any more.
When you are adding false as the second parameter to the json_encode it will updating all array to the sdClass empty objects.In this way you can the main array as the object
<?php
$json = '{
"buildings": "townhall",
"Army": {
"Paladins": {
"325648": 0,
"546545": 4
},
"Knights": {
"325648": -2,
"546545": 0
}
}
}';
$array = json_decode($json, true);
$object = (object)$array;
var_dump($object->Army);
?>
OUTPUT
array(2) {
["Paladins"]=>
array(2) {
[325648]=>
int(0)
[546545]=>
int(4)
}
["Knights"]=>
array(2) {
[325648]=>
int(-2)
[546545]=>
int(0)
}
}
Working Demo
It's because the output from your json_decode looks like this:
object(stdClass)(
'buildings' => 'townhall',
'Army' => object(stdClass)(
'Paladins' => object(stdClass)(
325648 => 0,
546545 => 4
),
'Knights' => object(stdClass)(
325648 => -2,
546545 => 0
)
)
)
Army is a standard object so it can't know how to echo it. You can however var_dump it:
var_dump($phpArray->Army);
The easiest solution is to treat it as a normal array with:
$phpArray = json_decode($jsonlogcontents, true);
My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.
but according to this: http://www.php.net/manual/en/function.json-encode.php#94157 it won't.
I'm using flot so I need to have an array with numeric indexes returned but what I'm getting is this:
jsonp1282668482872 ( {"label":"Hits 2010-08-20","data":{"1281830400":34910,"1281916800":45385,"1282003200":56928,"1282089600":53884,"1282176000":50262,"1281657600":45446,"1281744000":34998}} );
so flot is choking. If I var_dump the array right before I call json_encode it looks like this:
array(7) {
[1281830400]=>
int(34910)
[1281916800]=>
int(45385)
[1282003200]=>
int(56928)
[1282089600]=>
int(53884)
[1282176000]=>
int(50262)
[1281657600]=>
int(45446)
[1281744000]=>
int(34998)
}
any ideas?
As zneak says, Javascript (and thus JSON) arrays cannot have out-of-order array keys. Thus, you either need to accept that you'll be working with JSON objects, not arrays, or call array_values before json_encode:
json_encode(array_values($data));
However, it looks like you're looking to display time series data with flot. As you can see on the flot time series example, it should be a two element array like so:
$.plot(
$('#placeholder'),
[[
[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]
]],
{
label: 'Hits 2010-08-20',
xaxis: {mode: 'time'}
}
)
Given your array (let's call it $data) we can get the proper JSON like so:
json_encode(
array_map(
function($key, $value) { return array($key, $value); },
array_keys($data),
array_values($data)
)
);
It's conceptually impossible. You cannot encode an array with fixed indices in JSON.
As a reminder, a JSON array looks like this:
[1, 2, 3, 4, 5]
There's no room to put indices there.
You should work on the Javascript side. Accepting that json_encode will return an object, you can convert this object into an array. That shouldn't be too hard.
function toArray(object)
{
var result = [];
for (var key in object)
{
if (!key.match(/^[0-9]+$/)) throw new Error("Key must be all numeric");
result[parseInt(key)] = object[key];
}
return result;
}
You can force json_decode() to produce arrays by passing TRUE as the second parameter, but you can't force json_encode() to produce arrays in the first place:
json_decode($json, TRUE); // force array creation
You can use array_merge to reindex a numerically indexed array, like this:
$a = array(2 => 3, 4 => 5);
$a = array_merge($a);
var_dump($a);
For flot, what you're asking for isn't actually what you want. You want an array of arrays, not an array of numbers. That is, you want something that looks like this:
[[1281830400, 34910],
[1281916800, 45385],
[1282003200, 56928],
[1282089600, 53884],
[1282176000, 50262],
[1281657600, 45446],
[1281744000, 34998]]
As for how to do that in PHP, I'm not sure.