且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP的爆炸阵列

更新时间:2023-12-04 13:40:58

试试这个...

  $ =在阵列('FOO_1 | bar_1','FOO_2 | bar_2','foo_3 | bar_3','foo_4 | bar_4','foo_5 | bar_5');的foreach(作为&放$,$ R){
  $ R =爆炸(|,$ R);
}$兰特= array_rand($,第3);

这是修改 $在对飞,所以它包含了你要找的嵌套阵列结构。

现在...

  $在[$兰德[0] [0] // FOO_1
$在[$兰特[0] [1] // bar_1$在[$兰特[1]] [0] // foo_3
$在[$兰特[1] [1] // bar_3$在[$兰特[2]] [0] // foo_5
$在[$兰特[2] [1] // bar_5

我想这就是你要找的东西。

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;
}

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.