从查询创建多个数组

时间:2016-01-10 18:08:10

标签: php mysql for-loop multidimensional-array laravel-5

我正在使用Charts4Php和laravel 5.1但是我需要从查询返回多数组结果到数据库

数组示例

Driver

数组返回

array(
  array(
   array('Charts',6),
   array('Apple',8),
   array('Hone',14),
   array('Gas',20))); 

从查询返回的数组

array:1 [
  0 => array:4 [
    0 => array:2 [
      0 => "Charts"
      1 => 6
    ]
    1 => array:2 [
      0 => "Apple"
      1 => 8
    ]
    2 => array:2 [
      0 => "Hone"
      1 => 14
    ]
    3 => array:2 [
      0 => "Gas"
      1 => 20
    ]
  ]
]

控制器

    array:1 [▼
    0 => {#193 ▼
    +"Apple": 55
    +"Car": 22
    +"House": 66
    +"Gas": 5
  }
]

查看仅包含一行

$p = new \chartphp();
$DB = DB::Table('users')->select('Apple','Car','House','Gas')->where('id', '=', '2')->get();
 $p->data = $DB;
 $p->chart_type = "pie";
$p->title = "";
  $out = $p->render('c2');
    return('pages.test')->with('out',$out);

2 个答案:

答案 0 :(得分:0)

考虑循环查询结果以将其转换为所需的多维结构。

示例

$fields = [];
foreach($DB as $ind => $val) {
  $fields[] =  [$ind, $val]
}
$data = [ $fields ]; //Finally wrap them inside an array

答案 1 :(得分:0)

在Mwaa Joseph的帮助下,我发现我必须识别两次而不是一次感谢你的帮助

foreach($DB as $ind => $val) {
                foreach($val as $x => $y){
                    $fields[] =  [$x, $y];
                }

}

返回数组

array:1 [▼
  0 => array:4 [▼
    0 => array:2 [▼
      0 => "Apple"
      1 => 55
    ]
    1 => array:2 [▼
      0 => "Car"
      1 => 22
    ]
    2 => array:2 [▼
      0 => "House"
      1 => 66
    ]
    3 => array:2 [▼
      0 => "Gas"
      1 => 5
    ]
  ]
]