PHP爆炸数组

时间:2010-09-12 23:03:40

标签: php arrays

我正在尝试从数组中获取随机值,然后进一步细分它们,这是初始代码:

$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

我想要的与上面相同,但每个'foo'和'bar'都可以通过自己的键单独访问,如下所示:

$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

我尝试通过foreach循环爆炸$ rand,但我显然犯了一些n00b错误:

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

3 个答案:

答案 0 :(得分:4)

你很亲密:

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

答案 1 :(得分:3)

试试这个......

$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);

即时修改$in“,因此它包含您正在寻找的嵌套数组结构。

现在...

$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

我认为这就是你要找的东西。

答案 2 :(得分:1)

foreach($rand as $r){
  $result = explode("|", $r);  
  array_push($array, $result);
}
相关问题