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
}
Related
I have a complex multi-dimensional array that looks something like
[name] => Marko Polo
[description] => New application
[number] => ABCD1234
[loans] => Array
(
[0] => Array
(
[id] => 123
[application_id] => 456
[loan_fees] => Array
(
)
[loan_parts] => Array
(
[0] => Array
(
[id] => 987
[loan_id] => 123
[product_id] => 49788
[product] => Array
(
[id] => 49788
[lender] => MAC
...
I need to create an efficient way of traversing this array and, for example having a set of rules to filter/modify the data.
For example, in the array there is [lender] => MAC, I want to have something like
loans.loan_parts.product.lender.MAC = 'Macquarie'
This would be in a config of sorts such that if the data array changed, it would be simply a matter of changing that dot notation to point to the new location of the lender value.
Using this, I need to filter the lender and modify it to be Macquarie instead of Mac.
I know that a big no-no these days is using too many foreach loops and I've looked into Collections, but because the inner arrays are not named, I don't believe Collections is possible.
As I say, I'd like to avoid the situation of
foreach
foreach
if (is_array())
foreach
eeewww!
How can I execute this in the most efficient manner due to the possible large size of the array and its complexity.
You can use array_walk_recursive with callback that will change behavior according to key of array.
<?php
//can pass variable by reference to change array in function
function handleMAC(&$item, $key)
{
if($key == 'lender'){
$item['MAC'] = 'your value';
}
}
array_walk_recursive($array, 'handleMAC');
?>
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 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 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.
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.