array_rand from multidimensional array

jlknauff

New member
Aug 25, 2008
237
1
0
PHP:
        $paragraph = $new_page[2][array_rand($new_page[2], $random)];

I'm getting an error with the following code when I try to pull a random number of values from an array (one level deep w/ in another array).

I know I could just pull the sub array out into it's own array and make this easy on myself, but that would be inefficient.

Any idea how to fix my code to work the way I want it to? Oh, if it makes a difference, my array is set up like this:

PHP:
Array
(
    [0] => name
    [1] => Array
        (
            [0] => data 1
            [1] => data 2
            [2] => data 3
        )

    [2] => Array
        (
            [0] => other data 1
            [1] => other data 2
            [2] => other data 3
        )

    [3] =>
    [4] =>
)
 


You are telling PHP to resolve the value at location $new_page[2][<an array of keys>]. Since you can't use an array as an offset, you are getting an error.
This code does what you want:

Code:
$arr = array( "eeny", "meeny", "miney", "moe" );

foreach( array_rand( $arr, 2 ) as $offset )
{
    $new[] = $arr[$offset];
}

print_r( $new );
 
I spent some more time working on it this morning and came up with this:

PHP:
        $random = rand(3, 10);
        shuffle($new_page[2]);
        $paragraph = implode(array_rand(array_flip($new_page[2]), $random));