Array Key 0 instead of the string only for JSON encode - php

I'm attempting to use json_encode on a php array. I have to structure the returned JSON as:
[
{"text": "Title1"},
{"text": "URL"}
]
I've tried the following, but I keep getting 0 as a key.
$xml = simplexml_load_file($url);
$title1 = $xml->results->result->jobtitle;
$snippet1 = $xml->results->result->snippet;
$url1 = $xml->results->result->url;
$arrays = array('text'=>$title1);
echo json_encode($arrays);
What am I doing wrong with my encoded array? How do I have it so that it doesn't return as 0?
{"text":{"0":"CDL-A Dry Bulk Drivers Wanted - Regional - OH, WV, PA"}}

Please try this: You have no mistake in json_encode.
$title1 = $xml->results->result->jobtitle;
...
$arrays = array('text'=>$title1[0]);

They way you are setting your array is incorrect. What you want to do is.
$array = [
['text' => 'hello'],
['text' => 'hello again'],
];
$encoded = json_encode($array);
print_r($encoded);
which returns
[
{"text":"hello"},
{"text":"hello again"}
]

Related

Problem with json_encode() it removes the "0" key from JSON string number in PHP

I need to call this value registered in a MySQL column:
{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}
With this form I get the JSON from the MySQL database:
$boosterResultant = $mysqli->query('SELECT boosters FROM player_equipment WHERE userId = '.$player['userId'].'')->fetch_assoc()['boosters']; //response: "{\"0\":[{\"Type\":3,\"Seconds\":-185}],\"1\":[{\"Type\":4,\"Seconds\":-144}]}"
I want to access what is in 'Seconds' to modify its value, so I use this form to modify it:
$boosterFinal = json_decode($boosterResultant,true);
$boosterFinal[0][0]['Seconds'] += 36000; //the value is changed successfully
echo "Output:", json_encode($boosterFinal); //out: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]]
Since I run $boosterFinal = json_decode($boosterResultant,true); I get this: [[{"Type":3,"Seconds":-185}],[{"Type":4,"Seconds":-144}]]
but I need to stay like this for update later in the DB:
{"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]} //good
//bad: [[{"Type":3,"Seconds":35815}],[{"Type":4,"Seconds":-144}]]
Edit: Thanks to #A. Cedano (link of answer in Spanish forum: here), I found the answer:
//This is the data that comes from the sample DB
$str='{"0":[{"Type":3,"Seconds":-185}],"1":[{"Type":4,"Seconds":-144}]}';
//Don't pass TRUE to json_decode to work as JSON as is
$mJson=json_decode($str);
$mJson->{0}[0]->Seconds+=36000;
//Object Test
echo $mJson; //Output: {"0":[{"Type":3,"Seconds":35815}],"1":[{"Type":4,"Seconds":-144}]}
If PHP sees that your array keys are ascending ints, it automatically converts them into an array (php.net/manual/en/function.json-encode.php)
You can disable this by passing the JSON_FORCE_OBJECT flag as a second param into json_encode: json_encode($boosterFinal, JSON_FORCE_OBJECT)
I had a similar problem, where JSON_FORCE_OBJECT didn't work. I had an array that looked like this:
<?php
$array = [
"someKey" => [
0 => "Some text....",
1 => "Some other text....."
]
];
Using json_encode with no flags I got a JSON object that looked like this:
{
"someKey": [
["Some text...."],
{"1": "Some other text....."}
]
}
This is clearly not what I had as the PHP object, and not what I want as the JSON object.
with the JSON_FORCE_OBJECT I got a JSON object that looked like this:
{
"someKey": [
{"0": "Some text...."},
{"1": "Some other text....."}
]
}
Which does fix the issuse I had, but causes another issue. It would add unnecessary keys to arrays that don't have keys. Like this:
$array = ["Sometext..."];
echo json_encode($array, JSON_PRETTY_PRINT|JSON_FORCE_OBJECT);
// {0: "Sometext..."}
We once again have the same issue, that the JSON object is not the same as the original PHP array.
Solution:
I used stdClass for the array that had numeric keys. and It encoded it to JSON correctly. code:
$array = [];
$stdClass = new stdClass();
$stdClass->{0} = "Some text...";
$stdClass->{1} = "Some other text....";
array_push($array, ["someKey" => $stdClass]);
$json = json_encode($array, JSON_PRETTY_PRINT);
echo $json;
//Output:
/*
{
"someKey": [
{"0": "Some text...."},
{"1": "Some other text....."}
]
}
*/
This is because PHP does not touch the indexes when encoding an stdClass.

PHP JSON Array - how to modify a json code Group by the same value

I grouped my table by objects with the same value with php foreach function
$data = json_decode($geo, true);
$out = [];
foreach($data as &$element) {
$out[$element['id']][] = [
'lng' => $element['lng'],
'lat' => $element['lat'],
'time' => $element['time']
];
};
$geo = json_encode($out);
later I got this result
"[{
"1":[{"lng":134.94157,"lat":36.871337,"time":1502159287}],
"2":[{"lng":134.94157,"lat":34.598832,"time":1502211838}],
"3":[{"lng":131.225,"lat":37.101667,"time":1502144333},{"lng":131.24,"lat":37.123333,"time":1502144343}]
}]"
now I want my data to be like this
[
[{"lng":134.94157,"lat":36.871337,"time":1502159287}],
[{"lng":134.94157,"lat":34.598832,"time":1502211838}],
[{"lng":131.225,"lat":37.101667,"time":1502144333},{"lng":131.24,"lat":37.123333,"time":1502144343}]
]
How can I do this?
First, json_decode() your initial JSON data. Then, move to the first index in the decoded data and only pick values of the array's values skipping the keys with the help of array_values().
<?php
$prev_json = '[{"1":[{"lng":134.94157,"lat":36.871337,"time":1502159287}],"2":[{"lng":134.94157,"lat":34.598832,"time":1502211838}],"3":[{"lng":131.225,"lat":37.101667,"time":1502144333},{"lng":131.24,"lat":37.123333,"time":1502144343}]}]';
$data = json_decode($prev_json,true);
$new_json = json_encode(array_values($data[0]));
echo $new_json;
Demo: https://3v4l.org/bFmYn
Update: Looking at your updated code, you could remove the $element['id'] from $out[$element['id']] and make it as $out[] = [..rest of your code..] and it should work.

Edit value in a json from an array

I hav an array like this:
Array
(
[fruit] => Banana
[country] => Canada
)
How can I update my json file with a loop with these new datas ?
My json is a file and it looks lile this:
{"fruit" : "Cherry", "country" : "Mexico", "weight" : "28"}
Note: I want to update the value fruit and country, not all the json.
Thanks.
As i said you can decode your json as an associative array (note the use of json_decode() with second parameter set on true), loop throw it and update it while iterating. Finally encode to json again as follow
$array = array('fruit' => 'Banana', 'country' => 'Canada');
$json = '{"fruit" : "Cherry", "country" : "Mexico", "weight" : "28"}';
$mjson = json_decode($json,true);
foreach($array as $key => $val) {
if(isset($mjson[$key])) {
$mjson[$key] = $val;
}
}
$jjson = json_encode($mjson);
print_r($jjson);
//Output: {"fruit":"Banana","country":"Canada","weight":"28"}
Live demo
$input = /** some json string **/
$json = json_decode($input, true); // to assoc array
// update values
$json["fruit"] = "Cherry";
$json["country"] = "Mexico";
$json["weight"] = "28";
$ouput = json_encode($json); // back to json
// save to file etc.
Does this help?
You can't directly edit the file like it is an object.
First you need to read the file, than decode json:
e.g:
$string='{"name":"John Adams"}';
$json_a=json_decode($string,true);
Remember if you use second parameter "true" in json_a you will get associative array. Something like this:
$json_a=array("name"=>"John Adams");
But if you want to have an object don't set second parameter:
$string='{"name":"John Adams"}';
$json_o=json_decode($string);
Here json_decode($string) returns an object. Now you can do this:
echo $json_o->name;
When you modify the json object, write it back to the file.

PHP: Give a name to an array of JSON objects?

I have managed to get data from database in PHP file.
From there(data.php),
$output = json_encode($result);
The result would be like this,
$output=[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]
So how do I give name "kitten" an array of kitty objects in php format?
For example like
"kitten":[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]
You have to wrap your result in another array on the 'kitten' key :
$output = json_encode(['kitten' => $result]);
Try this:
<?php
$kitty = array('kitten' => array());
$kitty['kitty'][] = array('kitty' => 'Tabby');
$kitty['kitty'][] = array('kitty' => 'Ruby');
$kitty['kitty'][] = array('kitty' => 'Silver');
var_dump($kitty);
var_dump(json_encode($kitty));
which results in: {"kitty":[{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]}
Use nested encode and decode
$json = '[{"kitty":"Whitely"},{"kitty":"Tabby"},{"kitty":"Ruby"},{"kitty":"Silver"}]';
echo json_encode(array('kitten' => json_decode($json)));
try to use this
$output['kitty'][] = json_encode($result);
$result =array('kitten'=> $output);
output
{
"kitten":[
{"kitty":"Whitely"},
{"kitty":"Tabby"},
{"kitty":"Ruby"},
{"kitty":"Silver"}
]
}

How do I remove an Attribute from a JSON String utilizing PHP

I have a JSON result in PHP that looks like the following:
[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},
{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]
I want to eliminate the Attributes (which contains Type and URL) so that the JSON result is flattened. So I'd like it to look more like:
[{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},
{"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"}]
What is the best way in PHP to eliminate every instance of attributes?
//assign the orignal string to variable $json
$json = '[{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ay6IAA"},"Id":"a03U00000015ay6IAA","Name":"ManagerID-00003"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015ZfJIAU"},"Id":"a03U00000015ZfJIAU","Name":"ManagerID-00001"},{"attributes":{"type":"Manager__c","url":"/services/data/v23.0/sobjects/Manager__c/a03U00000015axwIAA"},"Id":"a03U00000015axwIAA","Name":"ManagerID-00002"}]';
//decode the string with json_decode();
$decoded = json_decode($json);
//loop over the decoded array and populate array with Id and Name only
foreach($decoded as $d) $newarr[] = array('Id' => $d->Id, 'Name' => $d->Name);
//json encode the resulting array.
$finalJSON = json_encode($newarr);
Using json_decode(), array_map() and json_encode() should be easy enough:
function strip_arguments( $item){
$new_result = array(
'Id' => $item['Id'],
'Name' => $item['Name'],
)
return $new_result;
}
$array = json_decode( $input);
$array = array_map( 'strip_arguments', $array);
$input = json_encode( $array);
You of course may use unset() inside strip_arguments (instead of creating new array) but this will make sure any "new attribute" won't make it trough.
You can use return array(...) instead of declaring variable and chain operations to: json_encode(array_map( 'strip_arguments', json_decode( $input))); too :)
Using PHP's JSON's tools you can convert the JSON string into an array, from here use a simple foreach statement and REGEX to delete array entries.
Once this is done simply convert back into a JSON string using PHP functions and do with it as you please :-)
The functions I am thinking off are - json_decode, json_encode.
Thanks
Andrew

Categories