在PHP中创建多维数组

时间:2016-04-20 14:12:23

标签: php multidimensional-array

我有一个数据库查询结果,它是一个数组,如下所示:

[{"uid":29,"totalAmount":"5400.00"},
 {"uid":499,"totalAmount":"5400.00"},
 {"uid":507,"totalAmount":"3960.00"},
 {"uid":497,"totalAmount":"3960.00"},
 {"uid":498,"totalAmount":"3960.00"},
 {"uid":34,"totalAmount":"3960.00"},
 {"uid":21,"totalAmount":"3240.00"},
 {"uid":27,"totalAmount":"2880.00"},
 {"uid":500,"totalAmount":"2880.00"},
 {"uid":19,"totalAmount":"2700.00"},
 {"uid":22,"totalAmount":"2700.00"},
 {"uid":20,"totalAmount":"2520.00"},
 {"uid":23,"totalAmount":"2520.00"},
 {"uid":504,"totalAmount":"1800.00"},
 {"uid":496,"totalAmount":"1440.00"},
 {"uid":26,"totalAmount":"1260.00"},
 {"uid":491,"totalAmount":"1080.00"},
 {"uid":492,"totalAmount":"720.00"},
 {"uid":464,"totalAmount":"540.00"},
 {"uid":493,"totalAmount":"540.00"},
 {"uid":76,"totalAmount":"540.00"},
 {"uid":505,"totalAmount":"180.00"},
 {"uid":506,"totalAmount":"180.00"},
 {"uid":494,"totalAmount":"180.00"},
 {"uid":495,"totalAmount":"180.00"}]

从这个结果我想创建一个多维数组,如下所示:

[ 
    "0" =>
    [
        "0"=>["uid"=>29, "totalAmount"=>5400 ],
        "1"=>["uid"=>499, "totalAmount"=>5400]     
    ],

   "1" =>
   [
       "0"=>["uid"=>507, "totalAmount"=>3960 ],
       "1"=>["uid"=>497, "totalAmount"=>3960],
       "2"=>["uid"=>498, "totalAmount"=>3960 ],       
       "3"=>["uid"=>34, "totalAmount"=>3960],    
    ],
]
// and so on ...

我尝试过foreach

 $topEar = [];

        $amount = '';

        foreach( $topEarners as $te)
        {    
            array_push($topEar, [$te->uid=>$te->totalAmount]);
        }

       $topEar; 

2 个答案:

答案 0 :(得分:0)

您可以这样做:

$topEar = array();
$currAmountArray = array();
$amount = null;
foreach( $topEarners as $te) {
    if( !is_null($amount) && $te->totalAmount != $amount ) {
         array_push($topEar, $currAmountArray);
         $currAmountArray = array();
    }

    array_push($currAmountArray, $te);
    $amount = $te->totalAmount;
}
if( !empty($currAmountArray) ) {
   array_push($topEar, $currAmountArray);
}

print_r($topEar);

您在每次迭代中保存最后$totalAmount并且只要它没有更改 - 当$currAmountArray更改您时,您将值存储在名为$totalAmount的子数组中将值推送到主数组。

我还在foreach循环后添加了一个条件,以确保$currAmountArray中的最后一批数据也会被推送到主数组($topEar)。

答案 1 :(得分:0)

如果使用SQL无法获得所需的结构,那么这将是PHP中最简单的方法:

$topEarners = json_decode($json, true);

foreach($topEarners as $row) {
    $result[$row['totalAmount']][] = $row;
}
  • 将JSON解码为PHP数组
  • 使用totalAmount作为键
  • 循环并附加到数组

如果您想重置密钥:

$result = array_values($result);