douzhong2954 2012-05-15 10:01
浏览 40
已采纳

如何在数组中保留n个值?

My data

1 : "aaa"
2 : "bbb"
2 : "ccc"
3 : "ddd"
4 : "eee"
4 : "fff"
4 : "ggg"

How could I keep these value in PHP array ? Are there any for-loop implementation example ?

[edited] How to make this array from my data via for-loop php ?

$array = array(
   1 => array("aaa"), 
   2 => array("bbb", "ccc"), 
   3 => array("ddd"),
   4 => array("eee", "fff", "ggg")
);

[edited#2] My real code:

$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] this is what it print

...
23 33 "aaa"
24 34 "bbb" 
25 34 "ccc" 
26 35 "ddd" 
...
  • 写回答

2条回答 默认 最新

  • douwen1549 2012-05-15 10:29
    关注

    I'm guessing this is what you want. I'm also guessing that $v['aid'] contains the index of the new array you want and that $w['new_geom'] contains the values, e.g.: aaa, bbb etc

    $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++;           
        }   
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突