I have a databse class which returns an array of objects. I am trying to get multiple bits of data from this single query, in order to prevent having to run three queries.
I have stumbled upon array_count_values() [ https://www.php.net/manual/en/function.array-count-values.php ] which will be perfect for catching various bits of data about the result set which I can use. Although I can't figure out how to cast all the second dimensions into arrays without having to just foreach through the whole return which would be a little bad I think.
Does anyone have any ideas how I can convert my array of objects, as a whole into an array, to allow this game changing function to do it's magic?
Array
(
[0] => stdClass Object
(
[message_id] => 23185
[from_profile] => 3165
[to_profile] => 962
[parent_message_id] => 17111
[date_sent] => 2011年02月23日 05:48:25
[subject] => RE: hi
)
// etc
There is also the issue that I've just thought of whilst typing this question, sods law eh? That will the function be able to parse multiple dimensions?
-
What property from the objects are your counting? Or are you not counting values from the objects?Bailey Parker– Bailey Parker2011年03月01日 12:11:48 +00:00Commented Mar 1, 2011 at 12:11
-
I'm not sure, but do you mean something like array_walk_recusrive?Zirak– Zirak2011年03月01日 12:14:44 +00:00Commented Mar 1, 2011 at 12:14
-
Your expected result is not Clear.mickmackusa– mickmackusa ♦2019年08月23日 10:24:52 +00:00Commented Aug 23, 2019 at 10:24
5 Answers 5
Since you only want to alter the first dimension, you can use array_walk
$dbResultsArray = // db results here
array_walk($dbResultsArray, function(&$elem) { $elem = (array)$elem; });
$dbResultsArray is passed by reference so once array_walk has run your $dbResultsArray is already updated.
I'm using closures which require php 5.3+ but you can use create_function in older versions.
1 Comment
I am not much clear what you are talking about but there is a function which can count array elements as well as object properties.
Hence you do not need to convert object into array for this purpose.
1 Comment
You could probably try something like
$result = array_count_values(array_map(function ($message) {
return $message->id;
}, $messageArray));
Comments
This might be able to point you in the right direction;
http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
As far as muliple dimensions go, I'm not sure on that one. Hopefully the above is helpful though.
Comments
do a for loop on your array of objects, and typecast them as (array) and assign them back,
you won't need to go inside further nesting,it will only typecase topmost level.
eg;
$newArr = array();
foreach($myObjArr as $t){
$arr = (array)$t;
$newArr[] = $arr;
}