I have the following problem:
I'm iterating through an array of valid objects using foreach. When trying to access the resulting objects or their properties I am getting the notice I would be trying to access a non-object.
Here is the code:
$schema = json_decode($_POST['d']);
foreach ($schema->node as $node) {
var_dump($node);
if ($node->status == 1) {
$data = $node->id;
}
}
var_dump outputs the following:
object(stdClass)#5 (6) {
["status"]=>
int(0)
["id"]=>
int(1)
["title"]=>
string(6) "Sensor"
["script"]=>
string(24) "from eZness import swag;"
["x"]=>
int(60)
["y"]=>
int(80)
}
Thanks in advance.
UPDATE:
$schema = json_decode($_POST['d']);
foreach ($schema->node as $node) {
var_dump($node);
echo $node->status; //Funnily this works
$status = $node->status; //while this doesn't
if ($node->status == 1) { //and this doesn't as well
$data = $node->id;
}
}
But when removing the var_dump even the echo doesn't work anymore.
UPDATE:
Resolved. Had a look at the client part of the application, there was a problem with pushing NULL values in the $schema->node array which of course are non-objects.
You are trying to access $node->data, which does not exist.
Perhaps more of a workaround than an answer but: use
$schema = json_decode($_POST['d'],true);
When you pass true as the second parameter, you get back an associative array instead of an object.
You should be able to loop through it with this:
$schema = json_decode($_POST['d'],true);
foreach ($schema['node'] as $node) {
if ($node['status'] == 1) {
$data = $node['id'];
}
}
Related
1. Extracted from my laravel controller:
..
..
$data = json_decode($response, true);
return $data;
..
..
return view('homepage')->with('homeExclusives', $homeExclusives);
Here is a sample of the returned data, just a short version, since the returned feed is very large, but this will give you an idea of the way it's structured.
array(4) {
["success"]=> bool(true)
["status"]=> int(200)
["bundle"]=> array(2) {
[0]=> array(631) {
["StreetDirPrefix"]=> string(2) "SW"
["DistanceToStreetComments"]=> NULL
}
[1]=> array(631) {
["StreetDirPrefix"]=> string(2) "NE"
["DistanceToStreetComments"]=> NULL
}
}
I need to extract "StreetDirPrefix" value from [0] and [1], but I always get an error. Can someone help?
For the data in your example you might use array_column and specify StreetDirPrefix as the column key.
$res = array_column($array["bundle"], "StreetDirPrefix");
print_r($res);
Php demo
Without knowing what error you are getting my solution would be something like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
}
}
?>
I always like to validate arrays, so if your $data variable or the $data["bundle"] subsection are not arrays then you will not get anything. Not even an error.
I have a working example here:
https://www.seeque-secure.dk/demo.php?id=PHP+how+to+loop+over+nested+JSON+Object
EDIT:
(if i understand you correct)
When you have validated your array all you have to do is repeat the inner validation like this:
<?php
if (is_array($data) && is_array($data["bundle"]) ) {
foreach ($data["bundle"] as $tmpKey => $tmpVal) {
if (isset($tmpVal["StreetDirPrefix"])) {
echo $tmpKey." => ".$tmpVal["StreetDirPrefix"]."\n";
}
if (isset($tmpVal["UnparsedAddress"])) {
echo $tmpVal["UnparsedAddress"]."\n";
}
if (isset($tmpVal["SalePrice"])) {
echo $tmpVal["SalePrice"]."\n";
}
//...... ect.....
}
}
?>
Seems really easy, but I can't seem to figure it out...
I have a simple line that gets mysql results through wordpress like this:
$sql_results = $wpdb->get_results($sql_phrase);
Then I parse it as JSON and echo it: json_encode($sql_results);
However, I want to add other data before I parse it as JSON. But I'm not sure how.
$sql_results basically gets me a list of post ID's, title and category.
It looks like this in var_dump (this is just the first row):
array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
Now to start with something easy, I'd like all associative arrays inside the object to have the extra key-value. I tried the following but got an error:
500 Internal error.
foreach($sql_search as $key => $value)
{
$value['pic_img'] = "test";
$sql_search[$key]=$value;
}
$result=$sql_search;
$sql_results = array(1)
{
[0]=> object(stdClass)#2737 (7)
{
["ID"]=> string(4) "2700"
["post_title"]=> string(18) "The compact helmet"
["category"]=> string(5) "Other"
}
}
foreach($sql_results as $key=>$value)
{
$value->solution = 'good';
$sql_results[$key]=$value;
}
$result=$sql_results;
var_dump($result);
$test = array ( array("ID"=>"35", "name"=>"Peter", "age"=>"43"),
array("ID"=>"34", "name"=>"James", "age"=>"19"), array("ID"=>"31", "name"=>"Joe", "age"=>"40") );
foreach($test as $key=>$value)
{
$value['solution'] = 'good';
$test[$key]=$value;
}
$result=$test;
var_dump($result);
this is my array:
$array= array(3) {
[0]=> array(3) { ["name"]=> "one" ["com"]=> "com1" ["id"]=> "1" }
[1]=> array(3) { ["name"]=> "two" ["com"]=> "com2" ["id"]=> "2" }
[2]=> array(3) { ["name"]=> "three" ["com"]=> "com3" ["id"]=> "3" }
I need posibility to change values of name and com for specific id. I try some examples from Stack questions:
1.Link1
foreach($array as &$value){
if($value['id'] == 1){
$value['name'] = 'test';
$value['com'] = 'test';
break; // Stop the loop after we've found the item
}
}
But it don't work. no error but no result too.
2.Link 2
Again,no error message,but no result...
I also try a lot of other examples from Stack but fake,and finaly to write a question..
Buy,
P
Since you are not changing your array value that's why it's-not giving you desired output. Try this:-
foreach($array as $key => &$value){
if($key == 1){
$array[1]['name'] = 'test';// change value to original array
$array[1]['com'] = 'test'; //change value to original array
break; // Stop the loop after we've found the item
}
}
for($i=0;$i<count($array);$i++) {
if($array[$i]['id'] == 1) {
$array[$i]['name'] = 'test';
$array[$i]['com'] = '';
break;
}
}
print_r($array);
If you are able to change the array on creation I would recommend shifting the id to the array's key identifier. Would make life a lot easier to just do:
$array[1]['name'] = 'test';
Otherwise use the for loop posted above and look it up. (Right awnser)
I've been trying for hours now to get the title field from the json code. Below is my php code
$search = $_GET['search'];
$new = str_replace(' ', '+', $search);
$url = "http://api.themoviedb.org/3/search/movie?api_key=###&query=".$new;
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$title = $json_data->title;
echo $title;
this is the var dump of the json
array(4) { ["page"]=> int(1) ["results"]=> array(1) { [0]=> array(10) { ["adult"]=> bool(false) ["backdrop_path"]=> string(32) "/4uJZvmEMX6Z6ag3bzym5exLY9wI.jpg" ["id"]=> int(65) ["original_title"]=> string(6) "8 Mile" ["release_date"]=> string(10) "2002-11-08" ["poster_path"]=> string(32) "/dXzTrKwpbLpCqn8O70FUUhNbYQT.jpg" ["popularity"]=> float(3.792332418578) ["title"]=> string(6) "8 Mile" ["vote_average"]=> float(6.2) ["vote_count"]=> int(185) } } ["total_pages"]=> int(1) ["total_results"]=> int(1) }
the error i keep getting is Notice: Trying to get property of non-object
any help would be greatly appreciated.
$json_data = json_decode($json, true);
will return an array not object
so you need to use as
$json_data["title"];
NOTE : Your json decoded array is nested so you may need to use as in your case.
$json_data["results"][0]["title"];
Or better loop through and get the desired data.
I just started using PHP and I THINK this might help you... but i'n not sure
foreach($json_data as $key => $value){
if($key == "results"){
$json_data2 = $value;
}
}
foreach($json_data2 as $key => $value){
if($key == "original_title"){
$title = $value;
}
}
echo $title;
I'm playing around with foreach and Simple HTML dom there I'm trying to save down some links to a array. But my problem is that the result saves in two arrays instead of one array.
foreach($html->find('div[class^=voucher success]') as $q)
{
#$var = $q->find('a', 0)->href;
$pos = strpos($var, "/ut/");
if($pos === false)
{
$item[] = $var;
}
var_dump($item);
}
Dump:
array(1) {
[0]=> string(10) "/hm?v=2726" }
array(2) {
[0]=> string(10) "/hm?v=2726" [1]=> string(10) "/hm?v=2732"
}
Why is that? What have I done wrong?
It's not saving in two arrays. You're dumping the data at the end of every foreach loop. Therefore it dumps twice, because there is two loops in the foreach.
To see the final result of $item you need to dump after the foreach.
foreach($html->find('div[class^=voucher success]') as $q)
{
#$var = $q->find('a', 0)->href;
$pos = strpos($var, "/ut/");
if($pos === false)
{
$item[] = $var;
}
}
var_dump($item);
The output would now be:
array(2) {
[0]=> string(10) "/hm?v=2726" [1]=> string(10) "/hm?v=2732"
}
Why do you think it is in two arrays? Your var_dump is inside your loop, so it is just dumping each time you iterate.