我的数据
1 : "aaa"
2 : "bbb"
2 : "ccc"
3 : "ddd"
4 : "eee"
4 : "fff"
4 : "ggg"
我如何在PHP数组中保留这些值? 是否有任何for循环实现示例?
[编辑] 如何通过for-loop php从我的数据中创建这个数组?
$array = array(
1 => array("aaa"),
2 => array("bbb", "ccc"),
3 => array("ddd"),
4 => array("eee", "fff", "ggg")
);
[编辑#2] 我的真实代码:
$list = "SELECT.....";
$root = retrieve($list);
// $root is a array of the data from PostgreSQL;
foreach($root as $i => $v){
if(cond) {
$q = "SELECT ...(use variables from $root)";
$a = retrieve($q);
for($a as $j => $w) {
echo $index." ".$v["aid"]." ".$w['new_geom']."<br />";
}
//what this line printed, i simplified to the sample data above
$index++;
}
}
[编辑#3] 这就是它打印的内容
...
23 33 "aaa"
24 34 "bbb"
25 34 "ccc"
26 35 "ddd"
...
答案 0 :(得分:4)
这很简单,只需使用嵌套的foreach循环
$array = array(
1 => array("aaa"),
2 => array("bbb", "ccc"),
3 => array("ddd"),
4 => array("eee", "fff", "ggg")
);
foreach($array as $num => $array2) {
foreach($array2 as $str) {
echo "\n".$num." : ".$str;
}
}
输出:
1 : aaa
2 : bbb
2 : ccc
3 : ddd
4 : eee
4 : fff
4 : ggg
答案 1 :(得分:1)
我猜这就是你想要的。我还猜测$v['aid']
包含您想要的新数组的索引,而$w['new_geom']
包含值,例如:aaa
,bbb
等
$list = "SELECT.....";
$root = retrieve($list);
$theNewArray = array();
foreach($root as $i => $v){
if(cond) {
$q = "SELECT ...(use variables from $root)";
$a = retrieve($q);
for($a as $j => $w) {
if (!array_key_exists($v["aid"], $theNewArray)) {
$theNewArray[$v["aid"]] = array();
}
$theNewArray[$v["aid"]][] = $w['new_geom'];
echo $index." ".$v["aid"]." ".$w['new_geom']."<br />";
}
//what this line printed, i simplified to the sample data above
$index++;
}
}