Decoding JSON string in PHP which has different headers - php

I am trying to decode a series of JSON messages
The JSON messgaes are received on an adhoc basis
If the JSON messages were all exactly the same format I would be fine. However they are not.
Here is an example of two different types.
object(stdClass)#11 (1) { ["SF_MSG"]=> object(stdClass)#12 (5) { ["time"]=> string(13) "1407962618000" ["area_id"]=> string(2) "NM" ["address"]=> string(2) "2B" ["msg_type"]=> string(2) "SF" ["data"]=> string(2) "FE" } }
object(stdClass)#13 (1) { ["CA_MSG"]=> object(stdClass)#14 (5) { ["to"]=> string(4) "0360" ["time"]=> string(13) "1407962618000" ["area_id"]=> string(2) "WH" ["msg_type"]=> string(2) "CC" ["descr"]=> string(4) "2S30" } }
One has a header of SF_MSG and the other CC_MSG
My question is "How do I in PHP distinguish between the different headers so I can read them in different ways
So for example echo '$Decodedjson->SF_MSG->time; will echo the time on the first one and
echo $Decodedjson->CC_MSG->to; will echo the to variable. However I need to know whether the header is SF_MSG or a CC_MSG before performing that task.
How do I read that Header title????? ie is it CC_MSG or SF_MSG ......$Decodedjson->?????
Thanks
EDIT
if ($con->hasFrame()){
$msg=$con->readFrame();
foreach (json_decode($msg->body) as $event) {
if(isset($event['SFG_MSG'])) {
$aid=($event->SF_MSG->area_id);
}
elseif(isset($event['CA_MSG'])) {
$aid=($event->CA_MSG->area_id);
}
echo $aid;

json_decode() requires true as the second parameter in order for the resultant object to be an associative array.
foreach (json_decode($msg->body, true) as $event)
once you do this, $event will be an associative array and no longer an object, so you will need to change the rest of your code to access $event as an array instead of an object.
// this won't work
$aid=($event->SF_MSG->area_id);
// change to this
$aid = $event["SF_MSG"]["area_id"];

Related

Accessing single elements PHP / mongoDB output

I have finally managed to retrive data from mongoDB within PHP. How ever I am not able to retrieve single elements from this array looking. I can only vardump() the cursor. How is it possible to print single elements from this array that seems to be made up of objects?
object(stdClass)#11 (7) { ["_id"]=> object(MongoDB\BSON\ObjectID)#9 (1) { ["oid"]=> string(24) "5a4a2cf55ff0f310cbf1c3a4" } ["Category"]=> string(9) "Allgemein" ["DateAdded"]=> object(MongoDB\BSON\UTCDateTime)#10 (1) { ["milliseconds"]=> string(13) "1514810613331" } ["Name"]=> string(4) "Welt" ["Website"]=> string(11) "www.welt.de" ["Active"]=> bool(true) ["Country"]=> string(2) "DE" }
I couldnt find anything on goolgle or PHP/mongodb documentation. Why cant I just do $array["_id"]? And how can I retrieve _id for example?
The resource is an object of stdClass. So you need to use:
echo $array->_id;
In case, if you want to use arrays, use get_object_vars() function. That way:
$array = get_object_vars($array);
echo $array["_id"];
And then you can use objects as arrays.

How to loop through multidimensional array?

I'm currently getting a JSON response from a company's API and converting it into a PHP array like this:
$api_url = file_get_contents('http://example.com');
$api_details = json_decode($api_url, true);
When I run var_dump on $api_details, I am getting this:
array(2) {
["metadata"]=>
array(5) {
["iserror"]=>
string(5) "false"
["responsetime"]=>
string(5) "0.00s"
["start"]=>
int(1)
["count"]=>
int(99999)
}
["results"]=>
array(3) {
["first"]=>
int(1)
["result"]=>
array(2) {
[0]=>
array(4) {
["total_visitors"]=>
string(4) "3346"
["visitors"]=>
string(4) "3249"
["rpm"]=>
string(4) "0.07"
["revenue"]=>
string(6) "0.2381"
}
[1]=>
array(4) {
["total_visitors"]=>
string(6) "861809"
["visitors"]=>
string(6) "470581"
["rpm"]=>
string(4) "0.02"
["revenue"]=>
string(7) "13.8072"
}
}
}
}
I'm trying to do 2 things and can't figure out how to do either with a multidimensional array.
I need to check to see if metadata > iserror is false. If it is not false, I want to show an error message and not continue with the script.
If it is false, then I wants to loop through the results of results > result and echo the total_visitors, visitors, etc for each of them.
I know how to echo data from array, I guess I'm just getting confused when there's multiple levels to the array.
Anyone that can point me in the right direction would be much appreciated :)
You can iterate over arrays using foreach. You can read up on it here: http://php.net/manual/en/control-structures.foreach.php
Since you're using associative arrays, your code will look something like this:
if ($arr['metadata']['iserror']) {
// Display error here
} else {
foreach($arr['results']['result'] as $result) {
echo $result['total_visitors'];
echo $result['visitors'];
}
}
You'll have to tweak the code to fit exactly what you're doing, but this should get you over the line.
Hope that helps!

How do I get the values out of the #attribute section?

I cannot figure out to get these values from this array. I need to know the code and name so my application knows which one to go for but I can't get the values out of there. Can someone please help me out? It's the values in the #attributes.
I'm using PHP by the way.
Thanks
array(2) {
[0]=>
object(SimpleXMLElement)#22 (2) {
["#attributes"]=>
array(2) {
["code"]=>
string(3) "HCD"
["name"]=>
string(31) "HIGH COST DELIVERY REGION SRCHG"
}
[0]=>
string(5) "71.25"
}
[1]=>
object(SimpleXMLElement)#24 (2) {
["#attributes"]=>
array(2) {
["code"]=>
string(3) "HCD"
["name"]=>
string(31) "HIGH COST DELIVERY REGION SRCHG"
}
[0]=>
string(5) "71.25"
}
}
Using SimpleXML, you're able to access the attributes on an XML by using the elements as if it was an array ($xml->elementName['attributeName'], or using the ->attributes() method as previously given).
For example, given the following code:
$xml = new SimpleXMLElement('<root><item foo="bar"></item></root>');
If I wanted to access the foo attribute on the item element, I would access it like this:
echo $xml->item['foo'];
However, there's a catch: the value that is returned is actually an instance of SimpleXMLElement. To be able to store or use it, you will need to convert it to a primitive type:
echo (string)$xml->item['foo']; // now a string
echo (int)$xml->item['foo']; // now an integer
echo (bool)$xml->item['foo']; // now a boolean
I figured it out on my own.
$xmlResponse->AccessorialCharges->OtherAccessorialCharges[$i]['code'];

Foreach through an array with objects and return the values and keys

array(14) {
[0]=>
object(stdClass)#2 (2) {
["set_id"]=>
int(44)
["name"]=>
string(7) "Cameras"
}
[1]=>
object(stdClass)#3 (2) {
["set_id"]=>
int(38)
["name"]=>
string(11) "Cell Phones"
}
[2]=>
object(stdClass)#4 (2) {
["set_id"]=>
int(39)
["name"]=>
string(8) "Computer"
}
The Above is my Data.
I want to return the object names ["Set_ID"] etc and the value.
I have googled and googled and tried examples from here with various failures and now I'm giving up.
I have tried to simply manually return data - ie
foreach($result as $results2)
{
foreach($results2->name as $item)
{
echo "<pre>";
print_r($item);
echo "</pre>";
}
}
I have tried all sorts of flavors of it I had kind of hoped the above would at least return data and it didn't - just errored.
In the end, I'd like to be able to both pull names and data. I don't want to have to manually find element names and code it as $result->SET_ID or whatever - I want to be able to just feed SET_ID in as a variable. I think my problem lies with it being an array of objects and I cant access that object name and all..
Im a noob, so any kind of like detailed explanation wouldn't hurt my feelings so I can learn something.
Instead of foreach($results2->name as $item) use foreach($results2 as $item). $results2->name is not an array thus causing the error.
You can read about object iteration in PHP here
foreach($result as $results2)
{
echo $results2->name.' '.$results2->set_id;
}

Modify data in php codeigniter active record result without changing structure

I've got a codeigniter active record query that uses get('table_name')->result();
The output is below, what i'd like to do is unserialize(base_64_decode) the "venue_opening_hours" string and replace that string in the data structure with the result of the unserialized & base64_decoded data. I know i can array_walk to do this normally, but i don't see how to access that particular bit of data as an object within an array...
Thanks!
array(2) {
[0]=>
object(stdClass)#142 (4) {
["entry_id"]=>
string(2) "15"
["google-id"]=>
string(40) "552e7c08d3b86c14d130ebe43a0ba421d03a60ae"
["venue_opening_hours"]=>
string(148) "YToxOntzOjEzOiJvcGVuaW5nX2hvdXJzIjthOjE6e3M6NzoicGVyaW9kcyI7YToxOntzOjQ6Im9wZW4iO2E6Mjp7czozOiJkYXkiO3M6MToiNSI7czo0OiJ0aW1lIjtzOjQ6IjIzMTUiO319fX0="
["title"]=>
string(18) "Place Name"
}
[1]=>
object(stdClass)#143 (4) {
["entry_id"]=>
string(2) "18"
["google-id"]=>
string(40) "71d9c8e1f64f330637c96d30a0ae15533836a85e"
["venue_opening_hours"]=>
string(972) "YToxOntzOjEzOiJvcGVuaW5nX2hvdXJzIjthOjE6e3M6NzoicGVyaW9kcyI7YToxMDp7aTowO2E6MTp7czo1OiJjbG9zZSI7YToyOntzOjM6ImRheSI7czoxOiIxIjtzOjQ6InRpbWUiO3M6NDoiMjMzMCI7fX1pOjE7YToxOntzOjQ6Im9wZW4iO2E6Mjp7czozOiJkYXkiO3M6MToiMSI7czo0OiJ0aW1lIjtzOjQ6IjIzMTUiO319aToyO2E6MTp7czo1OiJjbG9zZSI7YToyOntzOjM6ImRheSI7czoxOiIxIjtzOjQ6InRpbWUiO3M6NDoiMjMxNSI7fX1pOjM7YToxOntzOjQ6Im9wZW4iO2E6Mjp7czozOiJkYXkiO3M6MToiMSI7czo0OiJ0aW1lIjtzOjQ6IjIzMzAiO319aTo0O2E6MTp7czo1OiJjbG9zZSI7YToyOntzOjM6ImRheSI7czoxOiIyIjtzOjQ6InRpbWUiO3M6NDoiMjMxNSI7fX1pOjU7YToxOntzOjQ6Im9wZW4iO2E6Mjp7czozOiJkYXkiO3M6MToiMiI7czo0OiJ0aW1lIjtzOjQ6IjIzMzAiO319aTo2O2E6MTp7czo1OiJjbG9zZSI7YToyOntzOjM6ImRheSI7czoxOiI0IjtzOjQ6InRpbWUiO3M6NDoiMjMzMCI7fX1pOjc7YToxOntzOjQ6Im9wZW4iO2E6Mjp7czozOiJkYXkiO3M6MToiNCI7czo0OiJ0aW1lIjtzOjQ6IjIzMzAiO319aTo4O2E6MTp7czo1OiJjbG9zZSI7YToyOntzOjM6ImRheSI7czoxOiI1IjtzOjQ6InRpbWUiO3M6NDoiMjM0NSI7fX1pOjk7YToxOntzOjQ6Im9wZW4iO2E6Mjp7czozOiJkYXkiO3M6MToiNSI7czo0OiJ0aW1lIjtzOjQ6IjIzNDUiO319fX19"
["title"]=>
string(24) "Other place name"
}
}
You'd access it using:
$array[0]->venue_opening_hours
in a for loop...
//foreach ($array as &$arrayItem)
//{
foreach ($arrayItem as &$object)
{
// extract and convert it...
//$openinghours = unserialize(base64_decode($object->venue_opening_hours));
// Update it...
$object->venue_opening_hours = $unserialize(base64_decode($object->venue_opening_hours));
}
//}
The &$object is a reference, so the assignment will change the value in the original result set...
Also I forgot to also loop the array ... I think! so added the outer loop :)

Categories