problem with SimpleXML and inclosed arrays - php

I'm having a problem with SIMPLE XML. I seem to have an array with dumping the whole object. However, when I try to access the array, I get a single element of the array back.
Here is the full dump:
SimpleXMLElement Object
(
[#attributes] => Array
(
[type] => array
)
[person] => Array
(
[0] => SimpleXMLElement Object
(
..........................
),
[1] => SimpleXMLElement Object
(
..........................
)
)
)
when I try to access the person array through $xml->person, instead of getting the array, I get the first element back. Any ideas?

From the SimpleXML Basic usage documentation in the PHP Manual:
NOTE: Properties ($xml->movie in previous example) are not arrays. They are iterable and accessible objects.
So, in your case, $xml->person is not actually an array, just an iterable object. It can be easily converted to an array with:
$persons = array();
foreach ($xml->person as $person) {
$persons[] = $person;
}

Related

PHP: Count stdClass objects within array

I have an array with stdClass objects as below. How would I count how many I have under Interviewee_Name?
Tried counting as I would do an array but get an error that I can't becaused of the stdClass Object and then unsure how to proceed from there
Array
(
[0] => stdClass Object
(
[Interviewee_Name] => Array
(
[0] => stdClass Object
(
[id] => rn_Interviewee_Name_DIR_27
[value] => Janusz Jasinski
)
)
)
This'll get the number of elements under Interviewee_Name, but it'll count all elements, not just objects.
count($arr[0]->Interviewee_Name)
However, if you really only want to get the objects in Interviewee_Name, you'll need to array_filter the array to get only the objects, and then count that new array:
count(array_filter($arr[0]->Interviewee_Name, function ($el) {
return (gettype($el) == 'object');
}));
The syntax for getting an element from an array looks like $arr['index'], but in this case Interviewee_Name is a property of an object so you need to use the object syntax: $obj->prop
$array = json_decode(json_encode($formData), True);
I added that to before looking to do a count and it worked!

PHP Node no longer exists SimpleXML

I have a SimpleXMLElement object that I got from parsing a response from oData. I'm looping through the children and it works well as long as it has children (the truth is I'm not even sure if they are its children or if its just a collection). This is how my code looks like:
$dataset = soapService->doSoapCall();
$array = $dataset->children()->children();
foreach($rawArray as $element)
{
$row['Something'] = (string)$element->Something;
$newArr[] = $row;
}
The problem is that this code throws an error of: PHP Node no longer exists SimpleXML. I've been trying to check for null or check the count of it but I keep getting the same error. When I look at it from the debugger in net beans it just says its type SimpleXMLElement but I doesn't have any other value or children. Please help.
Note: When I do print_r($array) i get this:
SimpleXMLElement Object ( )
When the object actually has data it returns this:
SimpleXMLElement Object ( [Table] => Array ( [0] => SimpleXMLElement Object ( [EventCode] => 10020 ) [1] => SimpleXMLElement Object ( [EventCode] => 10030 ) [2] => SimpleXMLElement Object ( [EventCode] => 10040 ) ) ) {"code":99200}

Recursively loop through php array and convert object elements to array storing their class names

I've been hours trying to figure this, i know i'm missing something obvious. This is the problem:
I have an array that some of its elements are objects, others are arrays and others are of other types. What i need is:
Loop through the array and convert the object elements into array elements.
Loop recursively (or whatever you want to call it) through these new array elements (the ones that were converted from objects) and the elements that already are array and perform the previous task (that is: convert the object elements into array elements).
Here's the gotcha: every time an object element is converted into array, the class name of the object has to be added as the first element of the array that is generated by converting the object.
Here is a simplified example:
Array:
Array
(
[0] => PhpParser\Node\Expr\Assign Object
(
[var] => PhpParser\Node\Expr\Variable Object
(
[name] => bar
)
[expr] => PhpParser\Node\Scalar\LNumber Object
(
[value] => 22
)
)
)
I need a function like this:
//$arr is the array previously posted
$arr = cool_object_to_array($arr);
var_dump($arr );
outputs
Array
(
[0] => Array
(
[0] => PhpParser\Node\Expr\Assign
[var] => Array
(
[0] => PhpParser\Node\Expr\Variable
[name] => bar
)
[expr] =>Array
(
[0] => PhpParser\Node\Scalar\LNumber
[value] => 22
)
)
)
The nesting level is unknown. It can be many arrays nested on objects nested on other objects or arrays, etc. The example is just very simplified. I need a solution that handles that too.
Thanks in advance for all your answers!
This should do it:
function cool_object_to_array($array) {
foreach ($array as $key => &$value) {
if (is_object($value)) {
$type = get_class($value);
$value = (array) $value;
array_unshift($value, $type);
}
if (is_array($value)) {
$value = cool_object_to_array($value);
}
}
return $array;
}

How to grab value from array

I am pulling an array from my DB that is saved in this format:
[categories] => [
{"category":"Exit Sign"},
{"category":"Leaving"},
{"category":"Illuminated"},
{"category":"Sign"},
{"category":"Red"},
{"category":"Warning Sign"},
{"category":"Above"}
]
How can I loop through each {} and get the category?
Edit: I have attempted passing each JSON array from my DB through json_decode() but I am getting the following error "json_decode() expects parameter 1 to be string, array given..." Any idea what would cause this?
Edit 2: Here is the var_dump output for just one row in my DB:
array(1) {
["categories"]=>
string(845) "[{"category":"Built Structure"},{"category":"The Americas"},{"category":"Sky"},{"category":"New York City"},{"category":"Manhattan - New York City"},{"category":"USA"},{"category":"History"},{"category":"Suspension Bridge"},{"category":"Brooklyn - New York"},{"category":"Brooklyn Bridge"},{"category":"Scenics"},{"category":"Skyscraper"},{"category":"River"},{"category":"Downtown District"},{"category":"East River"},{"category":"Cityscape"},{"category":"Bridge - Man Made Structure"},{"category":"City"},{"category":"Lighting Equipment"},{"category":"Arch"},{"category":"Urban Skyline"},{"category":"Architecture"},{"category":"Sunset"},{"category":"Night"},{"category":"Modern"},{"category":"Urban Scene"},{"category":"Tower"},{"category":"Famous Place"},{"category":"Gate"},{"category":"Outdoors"},{"category":"East"},{"category":"Travel"}]"
}
Got it! I had to pass $array['categories'] into json_decode and then it worked properly. Thanks everyone for your help!
Well, So you are new to this world. You are welcome.
Let your array value is names as $json. This value is a json format, so for access this value you need to decode them. You need to use a function called json_decode, which has two parameter, the first one is string where you pass your variable json, an second one is bool where you pass true or false.
You have to pass when you want your array as associative not object. Here i ignore the second option, so my return array is object.
After decoding your json string you have an array, now you have to use a loop foreach to browse all the elements of the array. As you can see in the resultant array below, the array is multi-dimensional so after applying a foreach loop you just reach the first depth. For getting the value of category you should need to use -> after $val which is the first depth array.
$json = '[{"category":"Exit Sign"},{"category":"Leaving"},{"category":"Illuminated"},{"category":"Sign"},{"category":"Red"},{"category":"Warning Sign"},{"category":"Above"}]';
$arr = json_decode($json); //Also you can pass $yourArr['categories'];
foreach($arr as $val){
echo $val->category."<br/>";
}
After decoding your array looks like:
Array
(
[0] => stdClass Object
(
[category] => Exit Sign
)
[1] => stdClass Object
(
[category] => Leaving
)
[2] => stdClass Object
(
[category] => Illuminated
)
[3] => stdClass Object
(
[category] => Sign
)
[4] => stdClass Object
(
[category] => Red
)
[5] => stdClass Object
(
[category] => Warning Sign
)
[6] => stdClass Object
(
[category] => Above
)
)
Result:
Exit Sign
Leaving
Illuminated
Sign
Red
Warning Sign
Above

Parsing a timestamp based PHP std class obkect

I have a PHP standard class object converted from json_decode of a REST call on an API which looks like :
Array
(
[1437688713] => stdClass Object
(
[handle] => Keep it logically awesome.
[id] => 377748
[ping] => stdClass Object
(
[url] => https://api.me.com
[id] => 377748
[name] => web
[active] => 1
[events] => Array
(
[0] => data_new
[1] => data_old
)
So far i had no issues in parsing any of the PHP objects. However this one is failing because i can not access the nested object elements using a key since 1437688713 is not assigned to a key and accessing an object is failing if i try to do this:
$object->1437688713->handle
Is there a way to access these elements ?
Update: one more thing, i would never know this value (1437688713) in advance. Just like a key. All i get is a stdclass object which i have to parse.
The outer part of your data is an array, not an object. Try:
$array['1437688713']->handle;
or if you don't know the key, you can iterate over the array (handy if it may contain multiple objects too):
foreach ($array as $key => $object) {
echo $key; // outputs: 1437688713
echo $object->handle; // outputs: Keep it logically awesome.
}
Get the first item from $object array
$first_key = key($object);
Use it with your response array,
$object[$first_key]->handle;
Or, the first element of array
$first_pair = reset($object)->handle;

Categories