looping through an array in : PHP - php

My JSON Array:
[\"{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx5,78.xxxxxx3\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":1,\\\"reciever\\\":\\\"+91xxxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"}\",\"{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx,78.xxxxx\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":2,\\\"reciever\\\":\\\"+91xxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"}\"]
I am passing this JSONArray as a part of POST Request in add Parameter.
My code for displaying the content of the Array
$jsonData = stripslashes($_POST['add']);
$phpArray = json_decode($jsonData,true);
foreach ($phpArray as $index => $record)
{
echo $record["caller"];
}
My Output is just two open curly brackets.
{{
I unable to understand whats wrong

Your JSON is invalid, There shouldn't be quotes around each array.
Fix what is generating it, if oyou cant the below will fix
$jsonData = stripslashes(stripslashes($jsonData));
$jsonData = str_replace(
array('"{', '}"'),
array('{', '}'),
$jsonData
);
$phpArray = json_decode($jsonData,true);
foreach ($phpArray as $index => $record)
{
echo $record["caller"];
}
Though use as a last resort, Fix the broken JSON before its sent is the best option. magic quotes is also removed from PHP. avoid using it
Output of above
+91xxxx+91xxxxx

You have problem with your json sting.
Try this :
$post = '[{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx5,78.xxxxxx3\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":1,\\\"reciever\\\":\\\"+91xxxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"},{\\\"mapurl\\\":\\\"http:\\\\\\/\\\\\\/maps.google.com\\\\\\/maps?q=17.xxxxx,78.xxxxx\\\",\\\"caller\\\":\\\"+91xxxxxx\\\",\\\"id\\\":2,\\\"reciever\\\":\\\"+91xxxxx\\\",\\\"timpestamp\\\":\\\"3\\\"}]';
$jsonData = stripslashes(stripslashes($post));
$phpArray = json_decode($jsonData,true);
foreach ($phpArray as $index => $record)
{
echo $record["caller"];
}

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/>';
}
?>

PHP foreach json_encode issues

I got problems with json_encode.
My code below:
$jsonfiles = array('http://example.com/myjsonishere.php'); //Here's my JSON
foreach ( $jsonfiles as $jsonfile ) {
//read the json file contents
$jsondata = file_get_contents($jsonfile);
//convert json object to php associative array
$data = json_decode($jsondata, true);
$json = json_decode(stripslashes($data));
foreach ((array)$json as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$grap_item1 = $line['grap1'];
$grap_item2 = $line['grap2'];
$grap_item3 = $line['grap3'];
// execute this insertion
mysqli_stmt_execute($stmt);
}
}
}
Without that stripslashes, json_last_error would show error number 4 but now it's 0, so I'm good to go.
Without (array) in first foreach PHP error pop up:
Invalid foreach argument
Even if I have tested after $json = json_decode(stripslashes($data)); line : if(is_array($json)) the test is TRUE but still the foreach will not work without (array)
Anyway, in theory, my code passes the first foreach, but if I put inside first foreach loop e.g. var_dumb($z) or whatever, it will not print anything. So I guess my code is stuck in the first foreach.
Please, let me know if I could provide more information.

Loop through JSON and store values to PHP arrays

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.

Simple Json in PHP

I have a simple task that does not work
I Have a json file..
When you decode with the 'true' bool as second param, you will get an associative array back. In your code snippet you then loop it out.
What you should do, is skip the loop and just access the data from the assoc array right away:
echo $array['navn'];
// The JSON object:
{"nr":"5250","navn":"Odense SV","adresser":"http://oiorest.dk/danmark/postdistrikter/5250/adresser"}
// Is equivalent to this php assoc-array:
array("nr" => "5250", "navn" => "Odense SV", "adresser" => "http://oiorest.dk/danmark/postdistrikter/5250/adresser");
try following
<?php
$url = "http://oiorest.dk/danmark/postdistrikter/5000.json";
$content = file_get_contents($url);
$array = json_decode($content, true);
foreach ($array as $key=>$val) {
echo $val;
}
?>

JSON and Arrays mixed up (in PHP)

This is what I get from my SQL selection. The data is correct, now I'd like to echo it by foreach.
Array ( [0] => stdClass Object ( [sql_column] => [{"1":"value1", "2":"value2", "3":"value3"}] ) )
What I've tried (and which didn't work) was:
$obj = json_decode($arr);
foreach($obj as $data){
echo $data->sql_column->1; //this should echo "value1", but it doesn't
}
Does anyone see my mistake? Thanks in advance!
If $arr is the array you posted then you can't json_decode it since it's an array and not a JSON string.
//First you need to get the string
$json = $arr[0]->sql_column;
//Then decode
$data = json_decode($json);
//Then loop
foreach($data as $key => $value){
echo "$key = $value \n";
}
Your json seems to be complicated (double dimensional array), but you can fetch values from it in this manner:
foreach($arr as $data){
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}
}
I hope you get an idea...
I used foreach for $arr to cover multi values, you can omit that if you want:
$data=$arr[0];
$json = json_decode($data->sql_column);
$temp = (array)$json[0];
foreach($temp as $k=>$v){
print($v."<br/>");
}

Categories