Parsing a JSON string with multiple arrays - php

I am trying to parse this JSON string
$json = {"fields":{
"relationshipStatus":[{"fieldId":4,"name":"Committed"},{"fieldId":2,"name":"Dating"},{"fieldId":6,"name":"Engaged"},{"fieldId":3,"name":"Exclusive"},{"fieldId":7,"name":"Married"},{"fieldId":8,"name":"Open Relationship"},{"fieldId":5,"name":"Partnered"},{"fieldId":1,"name":"Single"}],
"ethnicity":[{"fieldId":1,"name":"Asian"},{"fieldId":2,"name":"Black"},{"fieldId":3,"name":"Latino"},{"fieldId":4,"name":"Middle Eastern"},{"fieldId":5,"name":"Mixed"},{"fieldId":6,"name":"Native American"},{"fieldId":8,"name":"Other"},{"fieldId":9,"name":"South Asian"},{"fieldId":7,"name":"White"}],
}}
Using this foreach loop, ultimately I want to be able to take the data and use them as Select / List dropdowns on a form.
foreach($json['fields'] as $item){
foreach($item['relationshipStatus'] as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
foreach($item['ethnicity'] as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}
No matter how I try to pull the data out, I keep getting errors similar to:
Notice: Undefined index: relationshipStatus in
/Applications/MAMP/htdocs/updateprofile.php on line 126 Warning:
Invalid argument supplied for foreach() in
/Applications/MAMP/htdocs/updateprofile.php on line 126
What am I doing wrong?

The first foreach selects already relationshipStatus and ethnicity. Maybe the following changes show what I mean:
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}

Here, you iterating the JSON Object in a wrong way.The array values you want to fetch is actually under $json['fields']['relationshipStatus'].
var name = $json['fields']['relationshipStatus']['name'];
var fieldId = $json['fields']['relationshipStatus']['fieldId'];
=============================== OR ========================================
As described by the A.fink
foreach($json['fields'] as $key=>$item){
if ($key == 'relationshipStatus')
foreach($item as $relationship){
echo $relationship['name'] . " " . $relationship['fieldId'] . "<br/>";
}
else if ($key == 'ethnicity')
foreach($item as $ethnicity){
echo $ethnicity['name'] . " " . $ethnicity['fieldId'] . "<br/>";
}
}

Related

How to make foreach work with this PHP script - GET API

I'm working on a script that will retrieve API information of the 'near earth objects' from NASA's website. User selects date, api grabs the information and displays it. How do I fix the foreach in this script? would appreciate some help with this.
$jsonAsteroids = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($jsonAsteroids, true);
echo "<h4>Retrieving the first element (i.e. \"links\") of the JSON structure</h4>";
var_dump( $data["links"]);
echo "<h4>Retrieving the first element (i.e. \"next\") inside the \"links\" element</h4>";
echo( $data["links"]["next"]);
You were very close. Your main issue was that you used json_decode(..., true); which gives you an array, but then used the object->property syntax instead of object['property']. My suggestion is to use json_decode without the 2nd argument in this case.
Finally, your 2nd foreach was malformed.
<?php
$result = file_get_contents("https://api.nasa.gov/neo/rest/v1/feed?start_date=2018-08-01&end_date=2018-08-04&api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo");
$data = json_decode($result);
foreach ($data->near_earth_objects as $date => $objects) {
echo "<p>" . count($objects) . " objects detected on $date</p>";
echo "<ol>";
foreach ($objects as $object) {
echo "<li>" . $object->name . " <a href='" . $object->nasa_jpl_url . "'>" . $object->nasa_jpl_url . "</a><br>";
echo "Diameter of the object: " . $object->estimated_diameter->meters->estimated_diameter_min . "-" . $object->estimated_diameter->meters->estimated_diameter_max . " metres<br>";
echo "<ul>";
foreach ($object->close_approach_data as $close_approach) {
echo "<li>Close approach: " . $close_approach->close_approach_date . " traveling at a velocity of " . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "missing " . $close_approach->orbiting_body . " by " . $close_approach->miss_distance->kilometers . " km</li> ";
}
echo "</ul>";
}
echo "</ol>";
}

Loop through associative array and assign values

I have an array:
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
What I want is to loop through this array, which I have done, but I am now confused because I don't know how to get the output I desire.
foreach ($array as $key => $value) {
//echo $key . "\n";
foreach ($value as $sub_key => $sub_val) {
if (is_array($sub_val)) {
//echo $sub_key . " : \n";
foreach ($sub_val as $k => $v) {
echo "\t" .$k . " = " . $v . "\n";
}
} else {
echo $sub_key . " = " . $sub_val . "\n";
}
}
}
The above code loops through the array, but this line of code:
echo $sub_key . " = " . $sub_val . "\n";
gives me:
step_no = 1 description = Ensure that you have sufficient balance step_no = 2 description = Approve the request sent to your phone
when I change it to:
echo $sub_val . "\n";
it gives me:
1 Ensure that you have sufficient balance 2 Approve the request sent to your phone
But I what I truly want is:
1. Ensure that you have sufficient balance
2. Approve the request sent to your phone
Is this possible at all? Thanks.
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction) {
echo $instruction['step_no'] . '. ' . $instruction['description'] . "\n";
}
If it's HTML you may want to use <ol> and <li>.
It smells like you are not running this script in command line but in browser. If so, then \n makes no visual effect (unless within <pre> block) and you u must use HTML tag <br /> instead. Also, drop concatenation madness and use variable substitution:
echo "{$sub_key}. = {$sub_val}<br/>";
You can simple achieve this way
<?php
$instructions = array (
array("step_no"=>"1","description"=>"Ensure that you have sufficient balance"),
array("step_no"=>"2","description"=>"Approve the request sent to your phone")
);
foreach($instructions as $instruction){
echo $instruction['step_no'].'. '.$instruction['description'].PHP_EOL;
}
?>
Alway keep it simple.

How to add results of a foreach loop to a variable in PHP

foreach ($_SESSION["products"] as $cart_itm) {
$items = $cart_itm["code"]
. " - " . $cart_itm["qty"]
. " - " . $cart_itm["price"]
. "<br>" ;
echo $items;
}
I have this code which gets every item from my basket and displays them, the problem is when I try to use this variable elsewhere in my code, it only displays the last item in the array, I realised that this is becasue the for loop keeps overwriting the last value . Is there a way I could put all results into one variable or use the loop to assign them too different variables maybe?
I also tried to put
foreach ($_SESSION["products"] as $cart_itm) {
$items .= $cart_itm["code"]
. " - " . $cart_itm["qty"]
. " - " . $cart_itm["price"]
. "<br>" ;
echo $items;
}
after looking through the forum but that returns me with items is not defined
so I tried to put
$items= ("")
but still get the final result
Any help is appreciated, thanks
You can concatenate you variables together, but you have to initialize your variable first.
(Otherwise you can think of something like: 'I want to concatenate this string to nothing', so this is obvious not going to work, that's why you initialize your variable so, you can say: 'I want to concatenate this string to a empty string')
Something like this:
$items = "";
foreach ($_SESSION["products"] as $cart_itm) {
$items .= $cart_itm["code"] . " - " . $cart_itm["qty"] . " - " . $cart_itm["price"] . "<br>" ;
}
Or you can put them in a array with this:
$items = array();
foreach ($_SESSION["products"] as $cart_itm) {
$items[] = $cart_itm["code"] . " - " . $cart_itm["qty"] . " - " . $cart_itm["price"] . "<br>" ;
}
print_r($items);
$items = "";
foreach ($_SESSION["products"] as $cart_itm) {
$items .= $cart_itm["code"] . " - " . $cart_itm["qty"] . " - " . $cart_itm["price"] . "<br>" ;
}
echo $items;
$foo = '';
foreach ($loopable as $item) {
$foo = $foo.'-'.$item;
}
echo $foo;
Make sure to init that variable before the for loop

simplexml 'Trying to get property of non-object in' error

I'm trying to parse the XML of http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175
but I get this error, can't find whats wrong.
Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 9
<?php
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175');
for($i=0;$i<10;$i+=1) {
$namespaces = $rss->getNameSpaces(true);
$dc = $rss->children($namespaces['dc']);
echo "Title: " . $rss->channel->item[$i]->title . "<br>";
echo "Creator: " . $dc->channel->item[$i]->creator . "<br>";
echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
}
And my second question.
Why is this code only working properly at http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175 and not at other pages like http://www.mpgh.net/forum/external.php?type=RSS2&forumids=168
Notice: Trying to get property of non-object in C:\xampp\htdocs\crossfire\index.php on line 7
<?php
$rss = New DOMDocument();
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=168');
for($i=0;$i<10;$i+=1) {
if (substr($rss->channel->item[$i]->title, 0, 9) == '[Release]') {
echo "Title: " . $rss->channel->item[$i]->title . "<br>";
echo "Link: " . $rss->channel->item[$i]->link . "<br><br>";
} else {
echo 'Hoi<br><br>';
}
}
Thanks.
I think the problem is that $ith index of $rss->channel->item is not set or not an object.
Try this; it will expose the problem:
$rss = simplexml_load_file('http://www.mpgh.net/forum/external.php?type=RSS2&forumids=175');
if ($rss===null || !is_object($rss))
die('Failed to load xml file.');
if (!is_object($rss->channel))
die('Channel is not an object!');
foreach ($rss->channel->item as $item)
if (is_object($item)) {
$namespaces = $rss->getNameSpaces(true);
$dc = $rss->children($namespaces['dc']);
echo "Title: " . $item->title . "<br>";
echo "Creator: " . $item->creator . "<br>";
echo "Link: " . $item->link . "<br><br>";
}

Is there something wrong with this foreach code?

foreach ($data['tests'] as $testname => $tests) {
echo "<h1>Extraction $testname Tests</h1>\n";
$function = $testfunctions[$testname];
echo "<ul>";
foreach ($tests as $test) {
echo "<li>" . $test['description'] . ' ... ';
$extracted = $extractor->$function($test['text']);
if ($test['expected'] == $extracted) {
echo " <span style='color: green'>passed.</span></li>";
} else {
echo " <span style='color: red'>failed.</span>";
echo "<pre>Original: " . htmlspecialchars($test['text']) . "\nExpected: " . print_r($test['expected'], true) . "\nActual : " . print_r($extracted, true) . "</pre>";
}
echo "</li>";
}
echo "</ul>";}
I keep getting the error:
Warning: Invalid argument supplied for
foreach() in
C:\xampp\htdocs\test\runtests.php on
line 49
p.s. the beginning of the code is line 49, so the probelm starts with the foreach statment.
Whenever i see that, it tends to mean that the thing i'm trying to iterate through isn't an array.
Check $data['tests'] (and each inner $tests) to make sure it's not null/unset/empty, and that it's something iterable like an array. Also keep in mind that older versions of PHP (before 5.0?) don't do iterable objects very well.
One of the elements in $data["tests"] is probably not an array.
Add this before the foreach:
if (is_array($tests))
foreach ($tests as $test) {...

Categories