开发者

PHP explode array

开发者 https://www.devze.com 2023-01-16 08:38 出处:网络
I\'m trying to get random values out of an array and then break them down further, here\'s the initial code:

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] 开发者_JAVA百科//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;
}


You were close:

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


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.


foreach($rand as $r){
  $result = explode("|", $r);  
  array_push($array, $result);
}
0

精彩评论

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