Loop through JSON and store values to PHP arrays - php

I have a JSON with the Following structure.
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
I need the Itemname to be made into a PHP array, Unitprice into another one, Qty to another one and price to another one. How do I do that?

$getArray = get_object_vars(json_decode($json));
print_r($getArray);
echo $getArray[1]->Itemname;
echo $getArray[1]->unitprice;
you require get_object_vars as well for achieving your requirement.

<?php
$json =<<<JSONLIVES
{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}
JSONLIVES;
$items = json_decode($json, TRUE);
$item_names = array();
foreach($items as $key => $item) {
$item_names[] = $item['Itemname'];
}
Or Php >= 5.5
print_r(array_column($items, 'Itemname'));

You need a function called json_decode() to convert your json data into PHP array
$json = {
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
};
var_dump(json_decode($json));

You need to decode your Json by PHP's json_decode()
$decodeJson will return object then you can read Itemname and other values by using $val->Itemname in foreach loop
$json = '{
"1":{"Itemname":"dtfg","unitprice":"12","Qty":"4","price":"$48.00"},
"2":{"Itemname":"kjh","unitprice":"45","Qty":"7","price":"$315.00"},
"3":{"Itemname":"yjk","unitprice":"76","Qty":"8","price":"$608.00"},
"4":{"Itemname":"hgj","unitprice":"4","Qty":"45","price":"$180.00"}
}';
$decodeJson = json_decode($json);
foreach($decodeJson as $key=>$val) {
print_r($val);
}
Live Json decode

Try that:
$json = json_decode($json);
foreach($json as $obj){
echo $obj->name;
.....
}

After some research, I found out that the most efficientt way that solves my problem here would be to do like the following.
$cash=json_decode($new_json, true);
echo $arr3[1]['Itemname'];
echo $arr3[1]['unitprice'];
:
:
and so on.
This can be put into loops easily, fetched into HTML text-fields (as I want here in this scenario) and so on.

Related

Using foreach Loop In PHP To Parse Json

I'm using iTunes RSS generator to get HOT tracks, now I'm using following way to parse JSON:
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'][0]['collectionName'];
echo $cltn;
?>
Now, as we know that It'll return only 1 collectionName.
JSON request is returning 10 results. How can I get them all using foreach loop? I've used several ways but no success.
Since you didn't give the output of the array I assume the [0] index is what needs to be iterated.
You need to foreach the $obj['feed']['results'] by doing:
Foreach($obj['feed']['results'] as $cltn){
Echo $cltn['collectionName'];
}
Foreach over the results:
foreach ($obj['feed']['results'] as $result) {
echo $result['collectionName'] . '<br>' . PHP_EOL;
}
Based on the code you provided you can iterate the results to get all possible information from the artist/track list, for example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
function test_print($item, $key)
{
echo "<strong>".$key."</strong>: ".$item."<br>";
}
foreach($cltn as $key => $c) {
echo "Result No ".($key+1)."<br>";
array_walk_recursive($c, 'test_print');
}
in case you only want to show artistName and collectionName you can slightly modify the above example:
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
$cltn = $obj['feed']['results'];
foreach($cltn as $c) {
echo $c['artistName'].": ".$c['collectionName']."<br>";
}
You can try all the above in PHP Fiddle
Try like this way with foreach() to iterate your array in key=>value manner as you've decoded the json as an array not an object in php.
<?php
$json_string = 'https://rss.itunes.apple.com/api/v1/in/apple-music/hot-tracks/all/10/explicit.json';
$jsondata = file_get_contents($json_string);
$array = json_decode($jsondata,true);
# printing resulted array just for debugging purpose
print '<pre>';
print_r($array);
print '</pre>';
foreach($array['feed']['results'] as $key=>$value){
echo $value['collectionName'].'<br/>';
}
?>

How to edit JSON objects

I'm on PHP and I need to edit a JSON output to return only objects >=0 and divided by one hundred
Eg.
$json = {"data":[0,55,78,-32,-46,37]}
Needed
$json = {"data":[0,0.55,0.78,0.37]}
How this can be done?
Well, I know this is not the best practice, but if it's as simple as this, you can do the following.
$json = '{"data":[0,55,78,-32,-46,37]}';
// decoding the string to objects & arrays
$x = json_decode($json);
// applying a function on each value of the array
$x->data = array_map(
function($a)
{
if( $a >= 0 ) return $a/100;
else return null;
},
$x->data
);
// Removing empty values of the array
$x->data = array_filter($x->data);
// making a JSON array
$jsonData = json_encode(array_values($x->data));
// inserting a JSON array in a JSON Object
$json = '{"data":' . $jsonData . '}';
// here is your {"data":[0,0.55,0.78,0.37]}
echo $json;
Hope it helps !
Btw, I had to trick the json encode with array_values to prevent the creation of an object rather than an array for the data content. But I guess there is a better method that I just don't know ...
EDIT :
Find out the way :D
Once empty values removed from the array, just do :
$x->data = array_values($x->data);
$json = json_encode($x);
This will do the trick and it will not create issues with the rest of the object.
Alessandro:
Here's my approach, feel free to try. json_decode and a simple foreach can help you...
Code:
$json = array();
$result = array();
$json = '{"data":[0,55,78,-32,-46,37]}';
$decoded_json=json_decode($json, TRUE);
foreach ($decoded_json['data'] as &$value) {
if ($value >= 0){
$value = $value / 100;
$result[]=$value;
}
}
echo json_encode($result);
?>
Result:
[0,
0.55,
0.78,
0.37
]

PHP Cannot loop through nested JSON

I have an API which is returning some nested JSON data with multiple levels. My PHP code to loop through is below but I'm not getting any output:
$data = json_decode($output, true);
foreach($data as $item){
$title = $item->events->name->text;
echo $title;
}
An example of the data can be found here: http://i.imgur.com/Y55vl7n.png
I am trying to print the text name of each of the events (events->name->text)
There is a problem in your code, when you decode the json string, you use:
$data = json_decode($output, true);
It is converting everything to "array" (http://php.net/manual/en/function.json-decode.php), so you cannot access it like if they were objects.
You have to do:
foreach($data as $item){
$title = $item["events"]["name"]["text"];
echo $title;
}
Hope this helps!

Decoding json in array , editing array and encoding in json - PHP

I am newbee in php and trying to get json in array and wanna change key in that json below is my code :
$json = json_decode(file_get_contents('all_json_files/jobs.json'), true);
foreach ($json as $key=>$row){
foreach ( $row as $key=>$row){
foreach ( $row as $key=>$row){
foreach ($row as $key=>$row){
if(strcmp($key,"security_block")==0)
{
foreach ($row as $k=>$r){
if(strcmp($k,"job_payload_hash")==0)
{
$row[$k]['job_payload_hash']=$base64String;
print_r($row);
}
}
}
}
}
}
}
print_r($json);
Issue is print_r($row); is updating properly but print_r($json); does not print the updated string .
If the key could appear anywhere, the answer is pretty simple:
function update_hash(&$item, $key, $base64String)
{
if ($key == "job_payload_hash") {
$item = $base64String;
}
}
array_walk_recursive($json, 'update_hash', 'something');
Update
The structure is something different that previously assumed; while the above will work, probably the below is a more direct approach:
foreach (array_keys($json['jobs']) as $jobId) {
$json['jobs'][$jobId]['job']['security_block']['job_payload_hash'] = 'something';
}
You use $key & $row variable in multiple time. for this reason, value of $key is changed each time, so parent loop does not work..
You can use recursive function lik answer of #Ja͢ck .
this is because you have to save not in variables you defined after => in a foreach.
You have to store this in format:
$json[0][0] ... = $base64String;
OR
You have to add a new array like $result = array() before you write the foreach and then store it in $result.
Decode the JSON string using json_decode(), edit your resulting array, then use json_encode(); to return the array to a JSON encoded string.
Also, use array_key_exists() rather than comparing array key strings.
$array = json_decode($json);
if(array_key_exists("job_payload_hash", $array){
$array["job_payload_hash"] = base64encode($var);
}
$json = json_encode($array);

How to loop json and parse the value

This is my php code [EDITED]:
$redis_data = file_get_contents("http://example.org/data/data.txt");
That code returns the following json data:
{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302}
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302}
This is my code to looping parse the value:
$redis_data = file_get_contents("http://example.org/data/data.txt");
$redis_data = json_decode($redis_data, true);
foreach ($redis_data as $data) {
echo $data['Phone'];
echo "<br>";
}
But I got this errors:
Invalid argument supplied for foreach()
What am I doing wrong?
The data you trying to get is not well formatted json
[{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName": "Jones"}]
This is the json syntax.
and you are getting data in following format.
{"ANumber":"08122378673","BNumber":"500046","StartTime":"08122014102113","EndTime":"08122014104126","TrunkA":"S1JK2SBD1S","TrunkB":"N7JK2GSM1B","Customer":"PT.BNI","time":1407921302}
{"ANumber":"081351607600","BNumber":"14000","StartTime":"08122014102406","EndTime":"08122014103738","TrunkA":"S1JK2SSB1S","TrunkB":"EPJK2MNR0","Customer":"Bank Mandiri (CC_IB_Jasnita)","time":1407921302}
You may need to reformat your data string
You're trying to loop JSON - not PHP. You need to run json_decode (docs) on the your $redis_data variable before attempting to loop it.
$redis_data = json_decode($redis_data, true);
You need to decode the json before you can loop through it.
$redis_data = json_decode(file_get_contents("http://example.com/tes_files/data.txt"), true);
foreach ($redis_data as $data) {
echo $data['phone'];
}
Here is solution
$redis_data = explode( chr(10), file_get_contents("http://example.com/tes_redis/data.txt"));
foreach ($redis_data as $data) {
var_dump(json_decode($data));
$data = json_decode($data);
echo $data->Phone;
echo $data->StartTime;
echo $data->Customer;
//echo $data->ANumber;
//echo $data->BNumber;
}
you need to export data first.
first you have to convert json to array using json_decode function it will give array and after that you can loop
`
$jsonString =
'[{"Phone":"08XXXXX","StartTime":"121212","Customer":"Customer A","time":1407921302},
{"Phone":"08XXXXX0","StartTime":"111111","Customer":"Customer B","time":1407921302},
{"Phone":"08XXXXX","StartTime":"131313","Customer":"Customer C","time":1407921302} ]';
$array=json_decode($jsonString);
foreach ($arrayOfEmails as $data) {
echo $data->Phone."<br>";
}
`

Categories