php PHP爆炸数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3697008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP explode array
提问by Clarissa B
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:
我想要的与上面相同,但每个 '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
I've tried exploding $rand via a foreach loop but I'm obviously making some n00b error:
我试过通过 foreach 循环爆炸 $rand ,但我显然犯了一些 n00b 错误:
foreach($rand as $r){
$result = explode("|", $r);
$array = $result;
}
回答by Chris Laplante
You were close:
你很接近:
$array = array();
foreach ($in as $r)
$array[] = explode("|", $r);
回答by Lee
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.
这会$in
“即时”修改,因此它包含您正在寻找的嵌套数组结构。
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.
我想这就是你要找的。
回答by Máthé Endre-Botond
foreach($rand as $r){
$result = explode("|", $r);
array_push($array, $result);
}