PHP how to loop over nested JSON Object? - php

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.....
}
}
?>

Related

how i can get data query cake php in array var_dump?

i have a query in cake php
$sql ="select menu from ms_menu";
$result=advancedQuery($sql);
foreach ($result as $data ){
echo $data[0];
}
the case is :
the $data[0] show nothing ...
i try to
var_dump $result;
and the result is
output
array(1) { [0]=> array(1) { [0]=> array(1) { ["NAMA_MENU"]=> string(6) "Report" } } }
i need to get "Report" to my variabel..
anyone knows the problem ?? please help
First of all, var_dump(); is a function and you should use it like this : var_dump($result);
Here is your information hierarchy :
- $data
-- $data[0]
--- $data[0][0]
---- $data[0][0]['NAMA_MENU']
Here, you are trying to echo an array ($data[0]). It's not possible.
You can :
— Create a double recursive foreach :
foreach ($result as $data ){
foreach ($data[0] as $innerData ){
echo $innerData['NAMA_MENU'];
}
}
— Get directly your needed value inside the first foreach :
foreach ($result as $data ){
echo $data[0][0]['NAMA_MENU'];
}

PHP Change multidimensional array structure

Hello I've multidimensional array that looks like that:
array(13890) {
[0]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(111)
["nazwa"]=>
string(6) "DŻUMA"
}
["ProjectIcd"]=>
array(0) {
}
}
[1]=>
array(2) {
["Icd"]=>
array(2) {
["id"]=>
int(566)
["nazwa"]=>
string(7) "ŚWINKA"
}
["ProjectIcd"]=>
array(0) {
}
}
An so on.
I want to change it so it looks something like that:
array(13890) {
[0]=> array(2) {
["id"]=>
int(111)
["text"]=>
string(6) "DŻUMA"
}
How is this possible to do?
I want to add, I want to convert the array to json and feed it to select2 js in ajax.
Will that be a problem or not?
Short solution using array_map function:
// $arr is your initial array
$new_arr = array_map(function($a){
return ['id' => $a['Icd']['id'], 'text' => $a['Icd']['nazwa']];
}, $arr);
So you can simple create a new array and add there the values, which you want based on the old array. Then you convert the array to a json string with the php function json_encode():
$array = array("text"=>$old_array[0]["Icd"]["nazwa"]);
echo json_encode($array);
I hope this is something that you want.
$res = [];
$i = 0;
foreach($array as $arr) {
//get keys
if (count($arr) > 0) {
$keys = array_keys($arr);
// loop through the keys and fetch data of those keys
// put in array
foreach($keys as $key) {
if ($arr[$key]) {
$res[$i]['id'] = $arr[$key]['id'];
$res[$i]['text'] = $arr[$key]['nazwa'];
}
$i++;
}
}
}
print_r($res);
// To change array to json
echo json_encode($res);

Laravel Lumen | get single values from array

I have a problem for like 4 hours.
$getrank = DB::table('users')->select('codes')->orderBy('codes', 'desc')->get();
with var_dump($getrank); I see whats in the array.
So I got this:
array(6) {
[0] => object(stdClass)#62 (1) {
["codes"]=> int(584)
}
[1] => object(stdClass)#64 (1) {
["codes"]=> int(117)
} [2] => object(stdClass)#65 (1) {
["codes"]=> int(88)
} [3] => object(stdClass)#66 (1) {
["codes"]=> int(66)
} [4] => object(stdClass)#67 (1) {
["codes"]=> int(53)
} [5] => object(stdClass)#68 (1) {
["codes"]=> int(37)
}
}
But I want them seperated.
I tried a lot!
In the end I thought this could be my answer:
echo $getrank[0]['codes'];
echo $getrank[1]['codes'];
echo $getrank[2]['codes'];
echo $getrank[3]['codes'];
echo $getrank[4]['codes'];
echo $getrank[5]['codes'];
But no.
I want a ranking, and I just need the first 5 ([0]-[4]). What else can I do?
In the end I want every value as a string!
Ok, now by reading your comments I understand what is the result you expect.
$getrank = array_map(
function ($user) { return $user->codes; },
DB::table('users')->orderBy('codes', 'desc')->take(5)->get()
);
Does that get you what you want?
Just use the pluck() (or lists(), alias of pluck()) method for this.
$codes = DB::table('users')->orderBy('codes', 'desc')->take(5)->lists('codes');
echo '<pre>';
foreach($codes as $key => $code) {
echo 'code '.$key.': '.$code.PHP_EOL;
}
echo '</pre>';
Documentation here
You can try to add toArray(), this will convert result from database to array, so you can use the code you've provided at the end of your question
$getrank = DB::table('users')->select('codes')->orderBy('codes', 'desc')->get()->toArray();
foreach($getrank as $rank) {
echo $rank['codes'];
}
And if you want to cast codes value to string, it is just echo (string) $rank['codes'];

PHP Trying to get property of non-object for valid object

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'];
}
}

Checking for data if an array has data present

I am wanting to check if there is data present in an array of data so that I can preform a function. Would I just use in_array?
Array:
["OpenHomes"]=>
array(2) {
[0]=>
array(2) {
["Start"]=>
string(21) "/Date(1354323600000)/"
["End"]=>
string(21) "/Date(1354326300000)/"
}
Would I just do the following?
if(in_array($detail['OpenHomes']))
{
echo 'yes';
}else{
echo 'no';
}
I am wanting to check if there is anything present within OpenHomes.
try this
if(!empty($detail) && in_array('OpenHomes',$detail))
{
echo 'yes';
}else{
echo 'no';
}
you can also check by
if ($detail['OpenHomes']) {
or
if (count($detail['OpenHomes']) > 0) { ... }
Or this
if( !empty($details['openHomes']) )
{
//
}
else
{
//
}
You can also use:
count($detail['OpenHomes'])
or
sizeof($detail['OpenHomes']) // its alias, same function with different name
to get count of elements in that array, but that will count empty elements too.

Categories