Ambiguity in PHP array - php

I want to display the Itinerary details from developer.ean.com API. By passing the customer's Itinerary ID and Email ID I got the details of reservation.
The result is comming in json format so I decoded it and creating array by using :
$array=json_decode($result);
The problem is whatever the result comming from API contain problem like :
For some records it providing array like this:
[Itinerary] => stdClass Object
(
[HotelConfirmation] => Array
(
[0] => stdClass Object
(
[supplierId] => 13
[chainCode] => EP
[arrivalDate] => 07/24/2012
[departureDate] => 07/26/2012
)
[Hotel] => Array
(
[0] => stdClass Object
(
[hotelId] => 394808
[statusCode] => A
[name] => Barkston Youth Hostel
)
)
)
)
In this case the HotelConfirmation and Hotel is Array which contain [0] as object
and for some records it providing array like this:
[Itinerary] => stdClass Object
(
[HotelConfirmation] => stdClass Object
(
[supplierId] => 13
[chainCode] => EP
[arrivalDate] => 07/24/2012
[departureDate] => 07/26/2012
)
[Hotel] => stdClass Object
(
[hotelId] => 394808
[statusCode] => A
[name] => Barkston Youth Hostel
)
)
and In this case the HotelConfirmation and Hotel is itself an object
I providing only few data here actually its big array and I want to provide list of it. But the array containing ambiguity like this. How can I handle this issue. Is there any solution.
Thanks in advance.

Pass true as the second argument to json_decode. This will create an array instead of stdClass
$array=json_decode($result, true);

you can normalize the input like so:
// get objects as arrays
$array = json_decode($result, true);
// remove the sub-level [0], when necessary
foreach ($array as $key => $value) {
if (is_array($value[0])) {
$array[$key] = $value[0];
}
}
Then the result always looks the same:
[Itinerary] => Array
(
[HotelConfirmation] => Array
(
[supplierId] => 13
[chainCode] => EP
[arrivalDate] => 07/24/2012
[departureDate] => 07/26/2012
)
[Hotel] => Array
(
[hotelId] => 394808
[statusCode] => A
[name] => Barkston Youth Hostel
)
)

First do this:
$array = json_decode($result, true);
Which will convert objects into associative arrays
And do adjustment like this:
if (isset($array['HotelItineraryResponse']['Itinerary']['HotelConfirmation'][0])) {
$array['HotelItineraryResponse']['Itinerary']['HotelConfirmation'] = $array['HotelItineraryResponse']['Itinerary']['HotelConfirmation'][0];
}
It will definitly work.

You can use is_array() to check for it:
if (is_array($hotel)) {
$hotel = $hotel[0];
}

just change to this:
$array=json_decode($result,TRUE);
and handle arrays always?

Looks like you may have to account for both possibilities in your model... Checking to see if the hotel node contains and array or an obj and operating accordingly.

you can type case the object inside of an array.
$array = json_decode($result);
$array = (array)$array
or alternatively you can pass true as the second argument in your json_decode();
according to php documentation
When TRUE, returned objects will be converted into associative arrays.
$array = json_decode($result, true);

Check for object or array:
if( is_object($Itinerary -> HotelConfirmation)) {
// do one thing or nothing
} elseif( is_array($Itinerary -> HotelConfirmation)) {
$Itinerary -> HotelConfirmation = array_shift( $Itinerary -> HotelConfirmation );
}

Related

Extracting a property from an array of an array of objects

I've got an object, containing an array of objects, containing an array of values:
stdClass Object (
[devices] => Array (
[0] => stdClass Object (
[location] => 1
[delegate] =>
[type] => 1
[id] => 1234
[IP] => 1.2.3.4
[name] => host1
[owner] => user6
[security] => 15
)
[1] => stdClass Object (
[location] => 2
[delegate] =>
[type] => 1
[id] => 4321
[IP] => 4.3.2.1
[name] => host2
[owner] => user9
[security] => 15
)
)
)
I want to extract just the id and name into an array in the form of:
$devices['id'] = $name;
I considered using the array_map() function, but couldn't work out how to use it... Any ideas?
This will generate you a new array like I think you want
I know you says that delegate is an object but the print does not show it that way
$new = array();
foreach($obj->devices as $device) {
$new[][$device->id] = $device->name;
}
Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.
$devices = myfunction($my_object);
function myfunction($ob){
$devices = array();
if(isset($ob->devices)){
foreach($ob->devices as $d){
if(isset($d->delegate->name && isset($d->delegate->id))){
$devices[$d->delegate->id] = $d->delegate->name;
}
}
}
return($devices);
}
Im usually using this function to generate all child and parent array stdclass / object, but still make key same :
function GenNewArr($arr=array()){
$newarr = array();
foreach($arr as $a=>$b){
$newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
}
return $newarr;
}

How can I put JSON to MySQL with PHP loop?

I have JSON like this (from nested sorting)
[
{"id":13},{"id":14},
{"id":15,
"children":[
{"id":16},{"id":17},{"id":18}
]
},
{"id":19},{"id":20},
{"id":21,
"children":[
{"id":22}
]
}
]
how I PHP loop to put this JSON in MySQL
Thank you.
As with any valid JSON format string, you can use PHP's built-in json_decode to convert it into a parsable object and then loop through those parameters. In this case, from the JSON string you've given (which seems to be an array)
$array = json_decode($string);
foreach ($array as $val) {
//The object $val will be:
"id":13
}
If it's nested, you would do another foreach loop and detect for the property that needs to be looped. For example you could do this in a variety of ways (check for the "children" property, loop through the $val properties and check if it is an array, if it is then loop through that). Inside this foreach loop iteration, you can insert it, or do execute whatever statement you need to get it inside MySQL
Your question is pretty vague on the format and way you want it inserted. I'd suggest showing some code you've tried so other people can help you and know what direction you're going in. (that's probably the reason for the downvote, not mine by the way)
Looping through all the properties of object php
just put your valid json inside json_decode and assign it to a php array as below
//$php_arr = json_decode('YOUR_JSON');
$php_arr = json_decode('[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]');
/*comment the following 3 lines when done*/
echo "<pre>";
print_r($php_arr);
echo "</pre>";
/*comment the above 3 lines when done*/
output
Array
(
[0] => stdClass Object
(
[id] => 13
)
[1] => stdClass Object
(
[id] => 14
)
[2] => stdClass Object
(
[id] => 15
[children] => Array
(
[0] => stdClass Object
(
[id] => 16
)
[1] => stdClass Object
(
[id] => 17
)
[2] => stdClass Object
(
[id] => 18
)
)
)
[3] => stdClass Object
(
[id] => 19
)
[4] => stdClass Object
(
[id] => 20
)
[5] => stdClass Object
(
[id] => 21
[children] => Array
(
[0] => stdClass Object
(
[id] => 22
)
)
)
)
Now as you have PHP array do what ever you want like
foreach($php_arr as $arr){
if(!isset($arr['children'])){
$q = "insert into tbl(id) values('".$arr['id']."')";
}else{
//your logic
}
}
You need to use json_decode function to decode JSON data. Then use foreach loop to manipulate data.
Try example
$str = '
[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]
';
$json = json_decode($str);
//var_dump($json);
foreach ($json as $item)
{
//The object $val will be:
echo $item->id."<br />";
//You INSERT query is here
//echo "INSERT INTO table (field) VALUE ($item->id)";
$query = mysqli_query($conn, "INSERT INTO table (field) VALUE ($val->id)");
}

issue while converting stdclassobject to array in php

I have an array inside which I have stdclassObjects. I need to convert those stdClassObjects to arrays. Below is the array:
Array
(
[serial] => #253
[details] => stdClass Object
(
[Department] => stdClass Object
(
[value] => CI DATA CENTER
)
[City] => stdClass Object
(
[value] => NYC
)
)
[owner] => Drey
)
Could somebody please assist me?
The super lazy way is json_decode and json_encode:
$multiDimArray = json_decode(json_encode($multiDimObject), true);
The documentation on json_decode specifies the second parameter being:
assoc
When TRUE, returned objects will be converted into associative arrays.
function convertStdClassToArray($stdClass) {
$outputArray = [];
if (is_array($stdClass) || !empty($stdClass)) {
foreach ($stdClass as $field => $value) {
$outputArray[$field] = $this->convertStdClassToArray($value);
}
}
return $outputArray;
}

Get a variable value from a json decoded response

I have a json response which is decode into an array $data as
stdClass Object ( [outboundSMSMessageRequest] => stdClass Object ( [deliveryInfoList] => stdClass Object ( [deliveryInfo] => stdClass Object ( [address] => 8606142527 [deliveryStatus] => Submitted ) [resourceURL] => http://api-testmobile.com/smsmessaging/1/outbound/OPNHSE/requests/urn:uuid:0f55fd13-a419-4ad9-adec-3dcf63ca39c1/deliveryInfos ) [senderAddress] => OPNHSE [outboundSMSTextMessage] => stdClass Object ( [message] => Sam has requested a payment of Rs 10.00. ) [clientCorrelator] => [receiptRequest] => stdClass Object ( [notifyURL] => [callbackData] => ) [senderName] => [resourceURL] => http://api-openhouse.testingmobile.com/smsmessaging/1/outbound/OPNHSE/requests/urn:uuid:0f5-a419-4ad9-adec-3dcf63ca39c1 ) )
I want to store [deliveryStatus] => Submitted this "Submitted" into a variable.
I have tried $dStatus=$data['deliveryStatus']; but its not working :(
UPDATE
I tried to convert it to associative array by json_decode($data,TRUE);
Array ( [outboundSMSMessageRequest] => Array ( [deliveryInfoList] => Array ( [deliveryInfo] => Array ( [address] => 98989 [deliveryStatus] => Submitted ) [resourceURL] => http://api-otest.com/smsmessaging/1/outbound/OPNHSE/requests/urn:uuid:3b277b5b-cf79-4551-872f-16674499bc09/deliveryInfos ) [senderAddress] => OPNHSE [outboundSMSTextMessage] => Array ( [message] => sam has requested a payment of Rs 100.00 through payt.me . Kindly clickhttps://www.test.me/test to pay. ) [clientCorrelator] => [receiptRequest] => Array ( [notifyURL] => [callbackData] => ) [senderName] => [resourceURL] => http://api-test.com/smsmessaging/1/outbound/OPNHSE/requests/urn:uuid:3b277b5b-cf79-4551-872f-16674499bc09 ) )
I got this.Now how to get the deliveryStatus variable?
If you want to access it a an associative array, you should convert it like an associative array first. Pass TRUE as a second argument to json_decode function as described in docs: http://php.net/json_decode
It's because you're accessing the data in the wrong fashion. json_decode returns an object, so you need to access these fields as object properties. For example:
Instead of
$dStatus=$data['deliveryStatus'];
Try a member access format
$dStatus=$data->deliveryStatus;
If you want to access the data as an associated array, that's also quite simple.
When you call json_decode, pass true as the second parameter:
$myJson = json_decode($data,true);
Please refer to the document on json_decode for more information.
I suggest to look at the view-source of the HTML you are outputting, or to wrap the print_r in a <pre></pre> tag, so that you can see the structure more easily.
Also, the elements are of class Object, which means they are not an array, so you need to use -> to access the elements of your objects.
So if it is an object:
$data = json_decode($response);
$dStatus = $data->outboundSMSMessageRequest->deliveryInfoList->deliveryInfo->deliveryStatus;
If it is an array, then:
$data = json_decode($response, true);
$dStatus = $data['outboundSMSMessageRequest']['deliveryInfoList']['deliveryInfo']['deliveryStatus'];
You see, the deliveryStatus entry is nested in sub-objects in the first case, and in sub-arrays in the second case.

How to access stdclass object after a specific key value pair?

I have a stdclass object as shown below:
stdClass Object
(
[text] => Parent
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Laurence W. Lane Jr.
[url] => http://www.freebase.com/view/m/0c02911
)
)
)
I iterate over multiple such objects, some of which have
stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
I was wondering how I would access the "values" object if it comes after a "text" that has "Parent" as its value?
there are serveral ways to turn it to array:
First Solution:
$value = get_object_vars($object);
Second Solution:
$value = (array) $object;
Third Solution
$value = json_decode(json_encode($object), true);
to get value of converted array
echo $value['values']['0']['id'];
The alternate way to access objects var without convert the object, try
$object->values->{'0'}->id
Expanding (or rather minimalizing) upon answer by Somwang Souksavatd, I like accessing Object values like this:
echo get_object_vars($object)['values']['0']['id'];
I had the same issue, still not so sure why but I was able to get it working using this workaround:
$k2 ="1";
$elements = json_decode('{"id":"1","name":"User1"}');
//$elements['id'] == $k2; //****Not Working
$tmp = (object)$elements;
$tmp = $tmp ->id; //****Working
//$tmp =$elements['id'] ; //****Not Working
return $tmp == $k2;
I have to say that sometimes accessing the element as array works and some times not,(On PHP7 it worked for me but on PHP5.6 it didn't).
$elements can be Array to but I chose to demonstrate with json string.
I hope this helps somehow !!!
$Obj=stdClass Object
(
[text] => Named after
[values] => Array
(
[0] => stdClass Object
(
[id] => /m/0c02911
[text] => Stanford
[url] => SomeURL
)
)
)
$Values= $result->values;
$Item = $Values[0];
$id=$Item->id;
$text = $Item->text;
$url=$Item->url;
I'm doing the same thing and all I did was this;
<?php
$stdObject = json_decode($stdClassObject);
print $stdObject->values[0]->id;
this can help you accessing subarrays in php using codeigniter framework
foreach ($cassule['tarefa'][0] as $tarefa => $novo_puto_ultimos_30_dias) {
echo $novo_puto_ultimos_30_dias;
What you are looking for is the Object['values'][0]: 'values' is the keymap just like 'text', and [0] is the index inside that array you wish to access. so if you would like to get the id deep in the nest, you'd have to do something like
Object['values'][0]['id']
or
Object['values'][0]->id
which should give you /m/0c02911. But I have no idea how you are doing your loop, so you will have to adjust it to your needs and place proper variables where they need to go in that code in your loop. Not exactly sure which language you are working with.

Categories