I have an object structured like so:
Array
(
[0] => SimpleXMLElement Object ( [0] => Europe )
[1] => SimpleXMLElement Object ( [0] => South America )
[3] => SimpleXMLElement Object ( [0] => North America )
[4] => SimpleXMLElement Object ( [0] => Asia )
)
I am trying to sort the objects alphabetically. I've tried using sort() on the array as a whole, but it's not working. I am assuming it was just grabbing the name of the object, which is the same in all cases and sorting those instead. I am trying to access the text inside each object but can't seem to do it without bringing the 'SimpleXMLElement Object()' text with it. How would I access that text and perhaps recreate a new array with just the text values?
EDIT: I've tried the following:
$regions = sort($regions);
$regions = usort($regions);
Thanks!
You can use usort:
<?php
function pony_sorting($a, $b)
{
if ((string)$a[0] == (string)$b[0) {
return 0;
}
return ((string)$a[0] < (string)$b[0]) ? -1 : 1;
}
usort($a, "pony_sorting");
This will keep the data structure of your array. But if you don't care about your SimpleXML elements, just export it in a clean and more memory efficient array.
$clean = array();
foreach ($a as $simplexml)
{
$clean[] = (string)$simplexml[0];
}
Note the (string) cast, allowing to get the actual value of the simpleXmlElement.
Related
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;
}
I'm making a call to a REST API and it returns an array of objects. Some of them contain further arrays with objects inside, as in:
Array
(
[0] => stdClass Object
(
[OPPORTUNITY_ID] => 7443729
[CUSTOMFIELDS] => Array
(
[0] => stdClass Object
(
[CUSTOM_FIELD_ID] => OPPORTUNITY_FIELD_7
[FIELD_VALUE] => Zorem
)
[1] => stdClass Object
(
[CUSTOM_FIELD_ID] => OPPORTUNITY_FIELD_8
[FIELD_VALUE] => Zappem
)
)
)
[1] => stdClass Object
(
[OPPORTUNITY_ID] => 7401996
[CUSTOMFIELDS] => Array
(
[0] => stdClass Object
(
[CUSTOM_FIELD_ID] => OPPORTUNITY_FIELD_7
[FIELD_VALUE] => Aorem
)
[1] => stdClass Object
(
[CUSTOM_FIELD_ID] => OPPORTUNITY_FIELD_8
[FIELD_VALUE] => Arappem
)
)
)
// [etc.]
)
What I would like to do is sort the first-level objects in the array based on either OPPORTUNITY_ID or on CUSTOM_FIELD_ID / FIELD_VALUE.
As a scenario, a user would click on the link: "Sort by OPPORTUNITY_FIELD_7" and the array element [1] would become [0] because "Aorem" has a higher alphabetical value than "Zorem".
I've managed to sort the first level objects using usort:
function sort_results( $a, $b ) {
if ($a->OPPORTUNITY_ID == $b->OPPORTUNITY_ID) return 0;
else if ($a->OPPORTUNITY_ID > $b->OPPORTUNITY_ID) return -1;
else return 1;
}
usort( $json_opportunities, "sort_results" );
But I don't know how to get off first base on sorting by level 2 values like OPPORTUNITY_FIELD_7. Any suggestions? Do I need to push everything into an array and sort that way, or is there a way to sort without rewriting the array first?
We just need a more advanced callback for usort(). For example, sorting the array using OPPORTUNITY_FIELD_7 would compare these values:
$restArray[0]->CUSTOMFIELDS[0]->FIELD_VALUE
$restArray[1]->CUSTOMFIELDS[0]->FIELD_VALUE
Because OPPORTUNITY_FIELD_7 is a value in the same array as the value we use to sort rather than being its index, we need to first find the numeric index to which it belongs. This is done by looping through CUSTOMFIELDS until we find OPPORTUNITY_FIELD_7.
// callback for usort() using "OPPORTUNITY_FIELD_7"
function sort_OF7($a, $b) {
// get the index where "OPPORTUNITY_FIELD_7" is stored
foreach($a->CUSTOMFIELDS as $index => $arr) {
if($arr->CUSTOM_FIELD_ID == 'OPPORTUNITY_FIELD_7') {
$ai = $index;
break;
}
}
// again
foreach($b->CUSTOMFIELDS as $index => $arr) {
if($arr->CUSTOM_FIELD_ID == 'OPPORTUNITY_FIELD_7') {
$bi = $index;
break;
}
}
// compare values
return strcmp(
$a->CUSTOMFIELDS[$ai]->FIELD_VALUE,
$b->CUSTOMFIELDS[$bi]->FIELD_VALUE
);
}
This assumes OPPORTUNITY_FIELD_7 is always available in the objects.
We can quickly test it:
// test
$main = JSON_decode('[{"OPPORTUNITY_ID":7443729,"CUSTOMFIELDS":[{"CUSTOM_FIELD_ID":"OPPORTUNITY_FIELD_7","FIELD_VALUE":"Zorem"},{"CUSTOM_FIELD_ID":"OPPORTUNITY_FIELD_8","FIELD_VALUE":"Zappem"}]},{"OPPORTUNITY_ID":7401996,"CUSTOMFIELDS":[{"CUSTOM_FIELD_ID":"OPPORTUNITY_FIELD_7","FIELD_VALUE":"Aorem"},{"CUSTOM_FIELD_ID":"OPPORTUNITY_FIELD_8","FIELD_VALUE":"Arappem"}]}]');
print_r($main);
usort($main, 'sort_OF7');
print_r($main);
I have this simple array $tree in PHP that I need to filter based on an array of tags matching those in the array.
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
I tried using an anonymous function like so:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return in_array($array->tags, $selectedTags, true);
});
$selectedTags:
Array
(
[0] => client corp
)
The above is returning empty when I'd expect item 1 to be returned. No error thrown. What am I missing?
In case of in_array($neddle, $haystack). the $neddle must need to be a String, but you're giving an array that is why its not behaving properly.
But if you like to pass array as value of $selectedTags then you might try something like below:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return count(array_intersect($array->tags, $selectedTags)) > 0;
});
Ref: array_intersect
If I am reading the question correctly, you need to look at each object in $tree array and see if the tags property contains any of the the elements in $selectedTags
Here is a procedural way to do it.
$filtered = array();
foreach ($tree as $key => $obj) {
$commonElements = array_intersect($selectedTags, $obj->tags);
if (count($commonElements) > 0) {
$filtered[$key] = $obj;
}
}
I was going to also post the functional way of doing this but, see thecodeparadox's answer for that implementation.
I can't for the life of me work out a nice way of getting an array of objects like this (would actually be a much larger array from a db):
Array
(
[0] => stdClass Object
(
[name] => Canterbury
)
[1] => stdClass Object
(
[name] => West Coast
)
)
Into a single level array like this:
Array
(
[0] => Canterbury
[1] => West Coast
)
So that when I do a json_encode, it looks like this:
{"0":"Canterbury","1":"West Coast"}
Rather than this:
[{"name":"Canterbury"},{"name":"West Coast"}]
I've tried a variety of things, like using php's array combine and merge functions, but no luck.
Pretty simple:
$output = array();
foreach($objectArray as $oneObject)
$output[] = $oneObject->name;
echo json_encode($output);
Well, I think you just need to put the object's name attribute in place of the array's value:
foreach($array as $key => $value){
$value = $value->name
}
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.