【问题标题】:PHP array_column with foreach loopPHP array_column 与 foreach 循环
【发布时间】: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


【解决方案1】:

以下逻辑可能会对您有所帮助。源数组称为$arr,结果数组称为$newArr。

sn-p 遍历源数组中所有唯一的id,并累积伴随的text 值。

$newArr = [];
$ids = array_values(array_unique(array_column($arr, 'id')));
foreach ($ids as $key => $id) {
    foreach ($arr as $value) {
        if ($value['id'] === $id) {
            $newArr[$key]['id'] = $id;
            $newArr[$key][$value['type']] = $value['text'];
        }
    }
}

工作demo

【讨论】:

    【解决方案2】:

    您可以通过group By获取分组信息并执行您需要的任何操作

    $records = Table::select('id','text','type')->groupBy('type')->paginate(20)->toArray();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 2016-09-26
      • 2012-07-19
      • 2015-12-10
      • 1970-01-01
      • 2014-03-15
      相关资源
      最近更新 更多