Getting JSON data in PHP - php

I have a JSON data like this:
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
I know how to retrieve data from object "first" (firstvalue) and second (secondvalue) but I would like to loop trough this object and as a result get values: "hello" and "hello2"...
This is my PHP code:
<?php
$jsonData='{"hello":{"first":"firstvalue","second":"secondvalue"},"hello2":{"first2":"firstvalue2","second2":"secondvalue2"}}';
$jsonData=stripslashes($jsonData);
$obj = json_decode($jsonData);
echo $obj->{"hello"}->{"first"}; //result: "firstvalue"
?>
Can it be done?

The JSON, after being decoded, should get you this kind of object :
object(stdClass)[1]
public 'hello' =>
object(stdClass)[2]
public 'first' => string 'firstvalue' (length=10)
public 'second' => string 'secondvalue' (length=11)
public 'hello2' =>
object(stdClass)[3]
public 'first2' => string 'firstvalue2' (length=11)
public 'second2' => string 'secondvalue2' (length=12)
(You can use var_dump($obj); to get that)
i.e. you're getting an object, with hello and hello2 as properties names.
Which means this code :
$jsonData=<<<JSON
{
"hello":
{
"first":"firstvalue",
"second":"secondvalue"
},
"hello2":
{
"first2":"firstvalue2",
"second2":"secondvalue2"
}
}
JSON;
$obj = json_decode($jsonData);
foreach ($obj as $name => $value) {
echo $name . '<br />';
}
Will get you :
hello
hello2
This will work because foreach can be used to iterate over the properties of an object -- see Object Iteration, about that.

Related

PHP Object Iteration - Nested Structures

I'm iterating over an array of objects, some of them nested in a non-uniform way. I'm doing the following:
foreach($response['devices'] as $key => $object) {
foreach($object as $key => $value) {
echo $key . " : " . "$value . "<br>";
}
}
Which works...until it hits the next embedded array/object, where it gives me an 'Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 65' error
I'm relatively new to PHP and have thus far only had to deal with uniform objects. This output is far more unpredictable and can't be quantified in the same way. How can I 'walk' through the data so that it handles each array it comes across?
You should make a recusive function this means, the function call itself until a condition is met and then it returns the result and pass through the stack of previously called function to determine the end results. Like this
<?php
// associative array containing array, string and object
$array = ['hello' => 1, 'world' => [1,2,3], '!' => ['hello', 'world'], 5 => new Helloworld()];
// class helloworld
class Helloworld {
public $data;
function __construct() {
$this->data = "I'm an object data";
}
}
//function to read all type of data
function recursive($obj) {
if(is_array($obj) or is_object($obj)) {
echo ' [ '.PHP_EOL;
foreach($obj as $key => $value) {
echo $key.' => ';
recursive($value);
}
echo ' ] '.PHP_EOL;
} else {
echo $obj.PHP_EOL;
}
}
// call recursive
recursive($array);
?>
This prints something like this :
[
hello => 1
world => [
0 => 1
1 => 2
2 => 3
]
! => [
0 => hello
1 => world
]
5 => [
data => I'm an object data
]
]
I hope this helps ?

Get the element with array and object

I spent over 2 hours looking for the solution, and I leave it to you because I am completely blocked. I try to learn the object in PHP. I created a function that return me the result of an SQL query.
Here is the var_dump return :
object(stdClass)[6]
public 'name' =>
array (size=2)
0 =>
object(stdClass)[11]
public 'id' => string '1' (length=1)
1 =>
object(stdClass)[12]
public 'id' => string '5' (length=1)
I used a foreach to parse this, but I don't get directly the id of each element. And I especially don't want to use another foreach.
foreach($function as $key => $value){
var_dump($value->id);
}
But it doesn't work there.
Here is the function called who returns this result
public function nameFunction () {
$obj = new stdClass();
$return = array();
$request = $this->getConnexion()->prepare('SELECT id FROM table') or die(mysqli_error($this->getConnexion()));
$request->execute();
$request->store_result();
$request->bind_result($id);
while ($request->fetch()) {
$return[] = parent::parentFunction($id);
}
$obj->name = $return;
$request-> close();
return $obj;
}
And parent::parentFunction($id) returns :
object(stdClass)[11]
public 'id' => string '1' (length=1)
You are looping the object instead of array. Try to use this code
foreach($function->name as $key => $value){
var_dump($value->id);
}
Tell me if it works for you
This question might help you :
php parsing multidimensional stdclass object with arrays
Especially answer from stasgrin
function loop($input)
{
foreach ($input as $value)
{
if (is_array($value) || is_object($value))
loop($value);
else
{
//store data
echo $value;
}
}
}

PHP extract values from array

I'm trying to extract values from an array within an array. The code I have so far looks like this:
$values = $request->request->get('form');
$statusArray = array();
foreach ($values->status as $state) {
array_push($statusArray, $state);
}
The result of doing a var_dump on the $values field is this:
array (size=2)
'status' =>
array (size=2)
0 => string 'New' (length=9)
1 => string 'Old' (length=9)
'apply' => string '' (length=0)
When running the above I get an error basically saying 'status' isn't an object. Can anyone tell me how I can extract the values of the array within 'status'??
-> it's the notation to access object values, for arrays you have to use ['key']:
foreach ($values['status'] as $state) {
array_push($statusArray, $state);
}
Object example:
class Foo {
$bar = 'Bar';
}
$foo = new Foo();
echo $foo->bar // prints "bar"

How to access data in nested Std Object array in PHP

I need to access the data: 'hotelID', 'name', 'address1','city' etc. I have the following Std Object array ($the_obj) in PHP that contains the following data:
object(stdClass)[1]
public 'HotelListResponse' =>
object(stdClass)[2]
public 'customerSessionId' => string '0ABAAA87-6BDD-6F91-4292-7F90AF49146E' (length=36)
public 'numberOfRoomsRequested' => int 0
public 'moreResultsAvailable' => boolean false
public 'HotelList' =>
object(stdClass)[3]
public '#size' => string '227' (length=3)
public '#activePropertyCount' => string '227' (length=3)
public 'HotelSummary' =>
array (size=227)
0 =>
object(stdClass)[4]
public 'hotelId' => 112304
public 'name' => La Quinta Inn and Suites Seattle Downtown
public 'address1' => 2224 8th Ave
public 'city' => Seattle
public 'stateProvinceCode' => WA
public 'postalCode' => 98121
public 'countryCode' => US
public 'airportCode' => SEA
public 'propertyCategory' => 1
public 'hotelRating' => 2.5
I have tried the following for lets say to access the 'name':
echo $the_obj->HotelListResponse->HotelList->HotelSummary[0]->name;
Also I have tried to print each key and value pairs by using foreach loop but I keep on getting errors. Here is what I tried:
foreach ($the_obj->HotelListResponse->HotelList->HotelSummary[0] as $key => $value){
echo $key.' : '.$value.'<br />';
}
Here are the errors that I get:
Trying to get property of non-object
Warning: Invalid argument supplied for foreach()
Thank you everyone for answering, I have figured out the way to access the 'hotelID', 'name' and all other keys and value pairs in the deepest nest of the array.
I converted the Std Object array to an associative array, then I accessed each of the value by using the foreach loop:
foreach ($the_obj["HotelListResponse"]["HotelList"]["HotelSummary"] as $value){
echo $value["hotelId"];
echo $value["name"];
//and all other values can be accessed
}
To access both (Keys as well as values):
foreach ($the_obj["HotelListResponse"]["HotelList"]["HotelSummary"] as $key=>$value){
echo $key.'=>'.$value["hotelId"];
echo $key.'=>'.$value["name"];
//and all other keys as well as values can be accessed
}
Regarding to #Satya's answer I'd like to show simpler way for Object to array conversion, by using json functions:
$obj = ...
$tmp = json_encode($obj);
$objToArray = json_decode($tmp,true);
This way you can easily access array items. First you can dump structure...
try something like this :
$p=objectToArray($result);
recurse($p);
}
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
function recurse ($array)
{
//statements
foreach ($array as $key => $value)
{
# code...
if( is_array( $value ) )
{
recurse( $value );
}
else
{ $v=$value;
$v=str_replace("’",'\'',strip_tags($v));
$v=str_replace("–",'-',$v);
$v=str_replace("‘",'\'',strip_tags($v));
$v=str_replace("“",'"',strip_tags($v));
$v=str_replace("”",'"',strip_tags($v));
$v=str_replace("–",'-',strip_tags($v));
$v=str_replace("’",'\'',strip_tags($v));
$v=str_replace("'",'\'',strip_tags($v));
$v=str_replace(" ",'',strip_tags($v));
$v=html_entity_decode($v);
$v=str_replace("&",' and ',$v);
$v = preg_replace('/\s+/', ' ', $v);
if($key=="image")
{
if(strlen($v)==0)
{
echo '<'.$key .'>NA</'.$key.'>';
}
else
{
echo '<'.$key .'>'. trim($v) .'</'.$key.'>';
}
}
}
}
}

Different way to convert object to array using PHP

When use this code:
$array=(array)$yourObject;
The properties of $yourObject convert to index an array, but how can convert as one array, these means, the $yourObject be one index of $array and I echo $array[0] for access through object?!
Another way for question, please see this sample code:
<?php
$var1 = (string) 'a text';
$var2 = (array) array('foo', 'bar');
$var3 = (object) array("foo" => 1, "bar" => 2);
//It's OK.
foreach((array)$var1 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's OK.
foreach((array)$var2 as $v) {
echo $v."<br>";
}
echo "<hr>";
//It's NOT OK. I want through $var3 in output as an array with one index!
foreach((array)$var3 as $v) {
echo $v."<br>";
}
echo "<hr>";
?>
Other way:
I want use a variable in foreach but I not sure about type this, I want working foreach without error for any type variable (string, array, object,...)
For example I thinks must I have this sample output for some this types:
Output for $var1:
array
0 => string 'a text' (length=6)
Output for $var2:
array
0 => string 'foo' (length=3)
1 => string 'bar' (length=3)
Output for $var3:
array
0 =>
object(stdClass)[1]
public 'foo' => int 1
public 'bar' => int 2
And the end I sure the foreach return current result without error.
You mean to wrap your object inside an array?
$array = array($yourObject);
As mentioned by mc10, you can use the new short array syntax as of PHP 5.4:
$array = [$yourObject];

Categories