Loop json array in php - php

I know it's been asked many times and I've gone through a good 15 - 20 questions trying to figure out how to get it to work.
JSON
{"menu": {
"title":"Title One",
"link":"Link One",
"title":"Title Two",
"link":"Link Two"}
}
PHP
$string = file_get_contents("test.json");
$json_a = json_decode($string,true);
foreach($json_a['menu'] as $key => $value) {
echo $key . ": " . $value . "<br />";
}
This so far only displays
title: Title Two
link: Link Two
as opposed to
title: Title One
link: Link One
title: Title Two
link: Link Two
Also am I correct in thinking $json_a[menu] does not need apostrophes because $json_a is not a function? it works with or without.
Thanks in advance.

You can't have multiple entries with the same key in an array. While JSON might allow it, when it's parsed by PHP, the last definition of the key,value pair wins.
It looks like menu should be an array of objects instead:
{
"menu": [{
"title":"Title One",
"link":"Link One"
}, {
"title":"Title Two",
"link":"Link Two"
}]
}
PHP
foreach($json_a['menu'] as $value) {
echo $value['title'] . ": " . $value['link'] . "<br />";
}

Related

In php, cycle through array (returned from an api) for a specific description

For a small project i am doing, i am grabbing some data from an api.
the data returned is decoded as follows:
under members, the first number (in this case: 65385) is the members id.
If a members status is ok, i want to return this ID, and the members name.
I am able to return the members name, but not sure how to also get the ID
"members": {
"65385": {
"name": "phpnewb",
"days_active": 705,
"last_action": {
"status": "active",
"timestamp": "",
"relative": "51 minutes ago"
},
"status": {
"description": "Okay",
"details": "",
"state": "Okay",
"color": "green",
"until": 0
},
Now what i want is:
if under status -> Description it says "Okay" i want to return the members id & members name
which would id: 65385 & name: phpnewb in this case.
Now i have tried doing this by (the name part) like this (with $idcall_array beeing the decoded data):
foreach ($idcall_array['members'] as $member) {
if ($member['status']['description'] == "Okay") {
$name = $member['name'];
echo $name;
echo "</br>";
}
}
This returns the name as expected, i just have no idea how to also get the id, with a var_dump on members i don't see the ID anymore
I am not experienced with these things.
help is appreciated
edit:
when doing a var_dump($members)
i get:
array(5) { ["name"]=> string(7) "phpnewb"
i asume the array(5) is the int/number i need, but dont know how to extract this.
You need to catch the key of the foreach, in your case, the id of the member :
foreach ($idcall_array['members'] as $id => $member) {
echo $id . ' : ' . $member['name'] . '<br>';
}
NB: A correct break-line tag is <br> in HTML5.
foreach ($idcall_array['members'] as $id => $member) {
if ($member['status']['description'] == "Okay") {
$name = $member['name'];
echo $name;
echo "</br>";
}
}

Get values from JSON array in PHP with the following format?

I have got this array from the Android developer whom I am working with and I have to get the values of the key name from the following array:
[
{
"data":"[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status":1
}
]
I have tried doing the following:
<?php
$s = '[
{
"data": "[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
echo $obj[0]['data']
?>
Which gives me following output:
[
{
"name": "step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd "
},
{
"name": "step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf"
},
{
"name": "step 3 kkkkkkkkkk"
},
{
"name": "step 4 ljlejrhlflhgf dfhjk"
}
]
But I want just the values of the key name like:
step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd
step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf
step 3 kkkkkkkkkk
.
.
.
My question is similar to this one:
Get value from JSON array in PHP
except the format is different.
Can I get the values in this format? If so, how? If not, is the format incorrect?
Assuming $obj[0]['data'] actually has the JSON that you posted, just decode and extract the name columns:
foreach(array_column(json_decode($obj[0]['data'], true), 'name') as $name) {
echo $name;
}
First of all you have not a json-structure inside the "data" field, but just a string, which contains json data.
Therefore you did it wrong, when convert the data into a constant value. You have to double all backslashes first.
Then you can get the "data" element and perform json_decode once more.
<?php
$s = '[
{
"data": "[{\\"name\\":\\"step 1 kdfhghdkgjdf\\\\nkjdhfgkjhdkjghd\\\\nkdfjhgkjdhfg\\\\n\\\\n\\\\ndfjhgkjdfjhgdfgd\\\\n\\"},{\\"name\\":\\"step 2 dhfgkjdfhkhkjchjkfd\\\\ndkjhjdf\\\\njhkdfhkghdkfhgkdhg\\\\n\\\\n\\\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\\"},{\\"name\\":\\"step 3 kkkkkkkkkk\\"},{\\"name\\":\\"step 4 ljlejrhlflhgf\\\\n\\\\n\\\\ndfhjk\\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
$data = json_decode($obj[0]['data'], true);
foreach($data as $item) {
print($item['name'] . "\r\n");
}

Retrieve data from JSON based on the object index in PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a $abcd variable and the following is the output:
echo $abcd;
//Output:
{
"NID": 2,
"STS": "3",
"Options": {
"Model": "model value",
"Location": "location value",
"Price": "price value",
"Name": "Value"
}
}
In the "Options" I have 3 names and values of each. The names are not fixed and could be anythings and the number of objects in Options could be any from 0 to 100.
I'd like to know if there is any way (JSON format preferred) that I can assign the Names and their related values to two other variables.
$varName[0]=Model
$varValue[0]=model value
$varName[1]=Location
$varValue[1]=location value
$varName[2]=Price
$varValue[2]=price value
i'm not sure what is th logic behind this,
but you may accomplish this by using mix of array_key & array_values like following:
$abcd = '{
"NID": 2,
"STS": "3",
"Options": {
"Model": "model value",
"Location": "location value",
"Price": "price value",
"Name": "Value"
}
}';
$data = json_decode($abcd, true);
$keys = array_keys($data['Options']);
$values = array_values($data['Options']);
echo $keys[0] . " - " . $values[0]; // Model - model value
echo $keys[1] . " - " . $values[1]; // Location - location value
// ..... and so on.
live example: https://3v4l.org/GggRd
$data = json_decode($abcd, true);
foreach($data['Options'] as $index => $value) {
//do whatever you want
}
//or access them directly
$data['Options']['Model']
You dont need to assign them to anything else, just json_decode() the JSONString and they become a PHP Object you can use as is
$obj = json_decode($abcd);
echo $obj->Options->Model;
echo $obj->Options->Location;
echo $obj->Options->Price;
RE your comment#
I said that the names are varies and Model, Location and Price is just an example
then you could do
foreach ($obj->Options as $prop => $val) {
sprintf( '%s = %s', $prop, $val );
}

Extracting from subarray structure after json_decode [duplicate]

This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 7 years ago.
I'm new to PHP and I'm trying to use it to filter information from the New York Times' article search API. I'm still struggling to figure out how I can pull out the "web-url" and "snippet" from the JSON response even after looking through this similar question. I'm using json_decode to turn the response into an associative array. Here's my code
$data = file_get_contents($queryURL);
$jsondata = json_decode($data, true);
if (count($jsondata) != 0)
{
foreach($jsondata['response']as $key => $value)
{
echo "Key: " . $key . " Value: " . $value . " <br>";
}
}
This only prints out the words "array", "ok" and "copyright".
Here's a sample of the json:
"response": {
"meta": {
"hits": 25,
"time": 332,
"offset": 0
},
"docs": [
{
"web_url": "http://thecaucus.blogs.nytimes.com/2012/01/01/virginia-attorney-general-backs-off-ballot-proposal/",
"snippet": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"lead_paragraph": "DES MOINES -- Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"abstract": "Virginia's attorney general on Sunday backed off of a proposal to loosen the state's ballot access rules to allow more Republican presidential candidates to qualify.",
"print_page": null,
"blog": [ ],
"source": "The New York Times",
"multimedia": [ ],
"headline": {
"main": "Virginia Attorney General Backs Off Ballot Proposal",
"kicker": "The Caucus"
},
Try this. You need to loop through each of the docs
foreach ($jsondata['response']['docs'] as $doc) {
echo "web_url: " . $doc['web_url'] . " snippet: " . $doc['snippet'];
}
When you are looping through $jsondata['response']
then when your $key is meta (Similarly for other keys as well like docs etc) its $value is an array i.e
array(
"hits"=> 25,
"time"=> 332,
"offset"=> 0
)
So when you are trying to echo this $value it prints array as its a property of echo in php to print arrays as string "array".
I hope this makes clear what you are doing wrong!!!
You might need to do something like this
foreach($jsondata['response']as $key => $value)
{
// check if $jsondata['response'][$key] is an array using is_array()
// handle as per array
}
Learn about is_array

datatables and json formatting error with php

HI im having a little difficulty with dataTables and php. I'm echoing out json in the format below:
{"iTotalRecords":10,"iTotalDisplayRecords":10,"aaData":[[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:00:00"],[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:18:59"] ... ] }
Which inst working with my dataTable, However after validating the above in jsonlint.com/, i get the well formated version below:
{
"iTotalRecords": 10,
"iTotalDisplayRecords": 10,
"aaData": [
[
"1",
"15",
"1",
"long description long description long description long description",
"2012-02-25 00:18:59"
],
...
]
}
When I put this in a txt file it loads just fine. I also noticed that adding a line break in the "long description" part, it also doesn't work even with the one above. My guess is that the line break is messing with the format of the json, but how can I avoid this in my php script since everything is being word wrapped? I've tried \n in my echo code but it doesnt seem to create a newline.
The opening and closing curly braces { and } are not acceptable to DataTables. My guess is, it's considered an object rather than an array. Try this:
Use the following php function to create your JSON array:
$this->arrayJSON = $this->arrayPHPToJS($myArray);
public function arrayPHPToJS($phpArray) {
if (is_null($phpArray)) return 'null';
if (is_string($phpArray)) return "'" . $phpArray . "'";
if (self::is_assoc($phpArray)) {
$a=array();
foreach ($phpArray as $key => $val )
$a[]=self::arrayPHPtoJS($val);
return "[" . implode ( ', ', $a ) . "]";
}
if (is_array($phpArray)) {
$a=array();
foreach ($phpArray as $val )
$a[]=self::arrayPHPtoJS($val);
return "[" . implode ( ', ', $a ) . "]";
}
return json_encode($phpArray);
}
Use this array in JS script in your view (make sure there's no html escaping):
<script type="text/javascript">
var jsArray = <?php echo $arrayJSON; ?>;
$(function(){
var oTable = $('#mytable').dataTable( {
"aaData": jsArray,
....
});
});
</script>
sounds more like the number of columns set up in table/datatables doesn't match number of items in your json array
There seemsed to be an issue with one of my database values, it was starting on a new line, which cause the format of the json to be incorrect.

Categories