【发布时间】:2020-11-13 07:44:38
【问题描述】:
我有一个表,我从中获取一些列
$records=Table::select('id','text','type')->paginate(250)->toArray();
$data=$records->['data'];
我得到的输出是:-
array:250 [
0 => array:4 [
"id" => 1
"text" => "text1"
"type" => "A"
]
1 => array:4 [
"id" => 1
"text" => "text2"
"type" => "B"
]
2 => array:4 [
"id" => 1
"text" => "text3"
"type" => "C"
]
3 => array:4 [
"id" => 2
"text" => "text4"
"type" => "A"
]
4 => array:4 [
"id" => 2
"text" => "text5"
"type" => "B"
]
5 => array:4 [
"id" => 2
"text" => "text6"
"type" => "C"
]
6 => array:4 [
"id" => 3
"text" => "text7"
"type" => "A"
]
7 => array:4 [
"id" => 3
"text" => "text8"
"type" => "B"
]
8 => array:4 [
"id" => 3
"text" => "text9"
"type" => "C"
]....
]
我想将它转换为对象数组/数组数组,其中相同 id 的结果应该以这样的方式合并,即“类型”的值应该是键,“文本”的值作为值。以下是预期结果的示例:-
array:20 [
{
"id" => 1
"A" => "text1"
"B"=>"text2"
"C"=>"text3"
}
{
"id" => 2
"A" => "text4"
"B"=>"text5"
"C"=>"text6"
}
{
"id" => 3
"A" => "text7"
"B"=>"text8"
"C"=>"text9"
}...
]
我尝试过使用 array_column。
$sortedRecords = array_column($data, 'text','type');
使用 array_column,我可以将“类型”的值转换为键,将“文本”的值转换为其值。但我也无法获得如何显示 id 以及如何为每个不同的 id 循环,因为它只显示最后一个 id 的结果。
【问题讨论】:
-
如果有冲突怎么办?
标签: php laravel laravel-5 eloquent