0

我的数据

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

[edited#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++;           
    }   
} 

[edited#3] 这就是它打印的内容

...
23 33 "aaa"
24 34 "bbb" 
25 34 "ccc" 
26 35 "ddd" 
...
4

2 回答 2

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
于 2012-05-15T10:04:35.510 回答
1

我猜这就是你想要的。我还猜测它$v['aid']包含您想要的新数组的索引并且包含$w['new_geom']值,例如:aaabbb

$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++;           
    }   
}
于 2012-05-15T10:29:33.580 回答