Php 是否要以数组键和值的形式访问列?
Laravel检索关联数组的方法是什么,其中键是查询的第一列,值是第二列Php 是否要以数组键和值的形式访问列?,php,orm,laravel-5.1,Php,Orm,Laravel 5.1,Laravel检索关联数组的方法是什么,其中键是查询的第一列,值是第二列 User::select('id','type')->unknown(); 应返回: [ 2=>'s', 30=>'t', 32=>'x', ] 应该是: User::lists( 'type', 'id' )->all(); 我认为该方法不存在,但您可以对返回的关联数组使用,以获得所需的: $array = User::select( 'type', 'id' )->all(
User::select('id','type')->unknown();
应返回:
[
2=>'s',
30=>'t',
32=>'x',
]
应该是:
User::lists( 'type', 'id' )->all();
我认为该方法不存在,但您可以对返回的关联数组使用,以获得所需的:
$array = User::select( 'type', 'id' )->all();//get array of assoc arrays
$result = array_column($array, 'type', 'id');//column
这将返回一个数组,使用$array
的每个子数组中的id
键(即每个结果/assoc数组)作为键,使用类型
值作为值。因此,如果$array
如下所示:
$array = [
[
'id' => 1,
'type' => 'a',
],
[
'id' => 2,
'type' => 'b',
],
];
$result = [
1 => 'a',
2 => 'b',
];
array\u列
调用的结果如下所示:
$array = [
[
'id' => 1,
'type' => 'a',
],
[
'id' => 2,
'type' => 'b',
],
];
$result = [
1 => 'a',
2 => 'b',
];
注意array\u column
需要PHP 5.5或更高版本,如果您运行的是5.4,并且无法升级,请编写自己的函数,这非常简单:
function myArrayCol(array $in, $valKey, $idxKey = null)
{
$result = [];
foreach ($in as $sub) {
if (!is_array($sub)) {
throw new RuntimeException('myArrayCol requires a multi-dimensional array to be passed');
}
$value = isset($sub[$valKey]) ? $sub[$valKey] : null;
if ($idxKey === null || !isset($sub[$idxKey])) P
$result[] = $value;
} else {
$result[$sub[$idxKey]] = $value;
}
}
return $result;
}
请注意,此实现完全未经测试,但您得到了基本想法
更新 另外,正如@Mat所建议的,laravel确实有一种方法可以满足OP的需求,并显示:
返回OP在一行中搜索的结果。阅读问题,OP希望数组的键为
id
,值为数组中的类型值->all
将返回一个关联数组arrays@EliasVanOotegem不会的<代码>列表
完全满足OP的要求。。。。您的array\u列
内容是不必要的。这个答案需要更多的解释。@andrewtweber:没错,你没有注意到Mat改变了调用的方法。我已经更新了我的答案,包括列表
方法+添加了文档链接+对于这个答案,尽管再多解释一点也不会错,谢谢。我想前两个代码块应该是交换的。