从数据库中我得到以下样式的数据:
Array
(
[0] => stdClass Object
(
[id] => 2
[name] => edit_sites
)
[1] => stdClass Object
(
[id] => 1
[name] => view_sites
)
)
Laravel是否有任何内置方法可以通过以下键获取数据:
Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[name] => Array
(
[0] => view_sites
[1] => edit_sites
)
)
或者我需要自己做?
答案 0 :(得分:2)
不幸的是,没有,你必须自己做,虽然这很容易。
$processedData = array();
foreach($dbData as $row) {
foreach($row as $dbKey => $value) {
$processedData[$dbKey][] = $value;
}
}
答案 1 :(得分:0)
如果您将数据作为原始数组(您似乎是)获取,那么array_pluck
将完成您想要的大部分工作:
例如:
// you could use this wherever you needed the specific lists
$ids = array_pluck($results, 'id'); // [ 1, 2 ]
// or if you wanted the array exactly as asked for in the question:
$sortedArray = array(
'id' => array_pluck($results, 'id'),
'name' => array_pluck($results, 'name')
);
// [
// 'id' => [1,2],
// 'name' => [ 'view_sites', 'edit_sites' ]
// ]
如果您将结果视为某种Illuminate\Support\Collection
类(例如,来自Eloquent
查询),那么您可以使用lists
方法Collection
作为array_pluck
$results->lists('id'); // [ 1, 2 ]