开发者

PHP: Counting values in an array of objects

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() [ http://uk3.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
开发者_如何学JAVA

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?


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.


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.

count()

Hence you do not need to convert object into array for this purpose.


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.


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;
}


You could probably try something like

$result = array_count_values(array_map(function ($message) { return $message->id; }, $messageArray));

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜