tags:

views:

95

answers:

4
+1  Q: 

PHP explode array

I'm trying to get random values out of an array and then break them down further, here's the initial code:

$in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5' );
$rand = array_rand($in, 3);

$in[$rand[0]]; //foo_1|bar_1
$in[$rand[1]]; //foo_3|bar_3
$in[$rand[2]]; //foo_5|bar_5

What I want is same as above but with each 'foo' and 'bar' individually accessible via their own key, something like this:

$in[$rand[0]][0] //foo_1
$in[$rand[0]][1] //bar_1

$in[$rand[1]][0] //foo_3
$in[$rand[1]][1] //bar_3

$in[$rand[2]][0] //foo_5
$in[$rand[2]][1] //bar_5

I've tried exploding $rand via a foreach loop but I'm obviously making some n00b error:

foreach($rand as $r){
$result = explode("|", $r);  
$array = $result;
}
+1  A: 

You were close:

$array = array();
foreach ($in as $r)
    $array[] = explode("|", $r);
SimpleCoder
A: 

array_rand() returns keys, not values. So you shouldn't be looping through $rand, but through $in:

foreach ($in as $k => $v) {
    $in[$k] = explode('|', $v);
}

Everything in $in will be split, but it doesn't matter since $rand contains only as many random keys as you tell it to give you.

If you still only want to explode the values whose keys occur in $rand, you can:

foreach ($in as $k => $v) {
    if (in_array($k, $rand)) {
        $in[$k] = explode('|', $v);
    }
}
BoltClock
A: 
foreach($rand as $r){
  $result = explode("|", $r);  
  array_push($array, $result);
}
SinistraD
+1  A: 

Try this...

$in = array('foo_1|bar_1', 'foo_2|bar_2','foo_3|bar_3','foo_4|bar_4','foo_5|bar_5' );

foreach($in as &$r){
  $r = explode("|", $r);  
}

$rand = array_rand($in, 3);

That modifies $in "on the fly", so it contains the nested array structure you're looking for.

Now...

$in[$rand[0]][0] //foo_1
$in[$rand[0]][1] //bar_1

$in[$rand[1]][0] //foo_3
$in[$rand[1]][1] //bar_3

$in[$rand[2]][0] //foo_5
$in[$rand[2]][1] //bar_5

I think that's what you're looking for.

Lee
Worked perfectly, thanks!
Clarissa