2

I have this example of an array of objects and I need to randomize it each time I do a foreach loop.

Looks like shuffle works only on arrays.

One thing is that I cant convert this into an array, because then it will become a STD object which I can't use, because of the way my mapper works.

array(48) {
  [0] => object(Friends_Model_Friends)#142 (4) {
    ["_id":protected] => NULL
    ["_tal":protected] => object(stdClass)#194 (3) {
      ["thumb"] => object(stdClass)#196 (6) {
        ["id"] => string(8) "10884697"
        ["type"] => string(1) "2"
        ["gallery"] => string(1) "1"
      }
    }
    ["_friend":protected] => string(7) "3492149"
    ["_dependent_table":protected] => NULL
  }
  [1] => object(Friends_Model_Friends)#195 (4) {
    ["_id":protected] => NULL
    ["_tal":protected] => object(stdClass)#143 (3) {
      ["thumb"] => object(stdClass)#202 (6) {
        ["id"] => string(8) "11160632"
        ["type"] => string(1) "2"
        ["gallery"] => string(1) "1"
      }
    }
    ["_friend":protected] => string(7) "3301541"
    ["_dependent_table":protected] => NULL
  }
....

Any ideas on shuffling this?

edit: Zend_Debug::dump(shuffle($object)); returns bool(true)

8
  • 3
    You are telling, that you have an array, but then you say, that shuffle only works with arrays and you can't convert it [the array] into an array, because it will become an object? Sorry, but that makes completely no sense to me... Commented Jul 10, 2012 at 19:24
  • So, did you try shuffle() and it didn't shuffle the array? Commented Jul 10, 2012 at 19:24
  • @Patrioticcow What result do you get from the shuffle() call? In what way does it not work? Can you show the code you used to call it? Commented Jul 10, 2012 at 19:25
  • if i do Zend_Debug::dump(shuffle($object)); i get bool(true) Commented Jul 10, 2012 at 19:27
  • 3
    @Patrioticcow shuffle() shuffles the array, but returns a boolean. Commented Jul 10, 2012 at 19:28

3 Answers 3

4
<?php
$my_array;
echo '<pre>'; print_r($my_array); echo '</pre>';
shuffle ($my_array);
echo '<pre>'; print_r($my_array); echo '</pre>';
?>

Try this code

Sign up to request clarification or add additional context in comments.

Comments

3

But the objects are in an array, not another object so you can use shuffle...

Comments

3

Shuffle always returns a boolean:

bool shuffle ( array &$array )

So you can't return it like

return shuffle( $myAwesomeArray );

This is what I just did and I wondered why it didn't give anything back, as you're probably expecting your shuffled array back.

You just have to call it like this

shuffle( $myAwesomeArray );
return $myAwesomeArray;

And all should work just fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.