Laravel Eloquent 从数据库获取一维数组
Laravel Eloquent getting single dimensioned array from database
可能有一种开箱即用的方法可以为我做这一切!
我需要以 预期输出:
的形式获取数组(放入 select 框中)
array: [
"4" => "Siemens"
"5" => "Dell"
]
目前我在做(使用Eloquent):
$array = $this->get(['id','manufacturer'])->toArray();
产生:
array:2 [▼
0 => array:2 [▼
"id" => 4
"manufacturer" => "Siemens"
]
1 => array:2 [▼
"id" => 5
"manufacturer" => "Dell"
]
]
然后我在做:
$test = [];
$i=0;
$key='';
$value='';
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($it as $v) {
$i++;
if ($i % 2 == 0) {
$key = $v;
array_push($test,[$key=>$value]);
} else {
$value = $v;
}
}
产生:
array:2 [▼
0 => array:1 [▼
4 => "Siemens"
]
1 => array:1 [▼
5 => "Dell"
]
]
非常接近...!我有点卡在最后一点,但想知道是否有更好的方法来完全解决这个问题?
进一步挖掘后发现 Eloquent 的 pluck
方法正是实现了这一点
$manufacturers->pluck('manufacturer','id');
returns:
Collection {#562 ▼
#items: array:2 [▼
4 => "Siemens"
5 => "Dell"
]
}
Array_combine 和 array_column 可以满足您的需求。
$arr =[
0 => [
"id" => 4,
"manufacturer" => "Siemens",
],
1 => [
"id" => 5,
"manufacturer" => "Dell"
]
];
$res = array_combine(array_column($arr, "id"), array_column($arr, "manufacturer"));
Var_dump($res);
可能有一种开箱即用的方法可以为我做这一切!
我需要以 预期输出:
的形式获取数组(放入 select 框中)array: [
"4" => "Siemens"
"5" => "Dell"
]
目前我在做(使用Eloquent):
$array = $this->get(['id','manufacturer'])->toArray();
产生:
array:2 [▼
0 => array:2 [▼
"id" => 4
"manufacturer" => "Siemens"
]
1 => array:2 [▼
"id" => 5
"manufacturer" => "Dell"
]
]
然后我在做:
$test = [];
$i=0;
$key='';
$value='';
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($it as $v) {
$i++;
if ($i % 2 == 0) {
$key = $v;
array_push($test,[$key=>$value]);
} else {
$value = $v;
}
}
产生:
array:2 [▼
0 => array:1 [▼
4 => "Siemens"
]
1 => array:1 [▼
5 => "Dell"
]
]
非常接近...!我有点卡在最后一点,但想知道是否有更好的方法来完全解决这个问题?
进一步挖掘后发现 Eloquent 的 pluck
方法正是实现了这一点
$manufacturers->pluck('manufacturer','id');
returns:
Collection {#562 ▼
#items: array:2 [▼
4 => "Siemens"
5 => "Dell"
]
}
Array_combine 和 array_column 可以满足您的需求。
$arr =[
0 => [
"id" => 4,
"manufacturer" => "Siemens",
],
1 => [
"id" => 5,
"manufacturer" => "Dell"
]
];
$res = array_combine(array_column($arr, "id"), array_column($arr, "manufacturer"));
Var_dump($res);