迭代时按列值对查询结果行进行分组

问题描述 投票:0回答:4

我有一个数组:

$biaya = odbc_exec($koneksi,"SELECT * FROM example");
$no = 0;
while (odbc_fetch_row($biaya)) {
    $no++;
    $sub_title = odbc_result($biaya, "subtitle");
    $title = odbc_result($biaya, "title");
}

如果我显示循环,它将是这样的:

我想根据字幕分割数组。我想得到这样的数组:

我该如何解决这个问题?

php arrays grouping
4个回答
2
投票

你可以像下面这样做:-

$result = [];
foreach ($array as $row){
    $result[$row['subtitle']][] = $row;
}

0
投票
  1. 最好使用一些 PHP 适配器,如
    Eloquent
    Doctrine
    ,而不是运行原始查询。
  2. 使用

    order by

    从示例订单中按字幕选择 *

  3. while
    循环中,请使用以下技巧。

```

$temp = null;

$result = [];
while(odbc_fetch_row($biaya)) {
   $no++;
   $sub_title=odbc_result($biaya,"subtitle");
   $title=odbc_result($biaya,"title");
   if($temp != $sub_title) {
      $result[$sub_title] = ["no" => $no, "subtitle" => $sub_title, "title" => $title];
      $temp = $sub_title;


   }
   else {
      $result[$sub_title][] = ["no" => $no, "subtitle" => $sub_title, "title" => $title];
   }
}

```


0
投票

这里是解决方案..你可以看到结果这里(更新)

我更新了

Inventaris
类别

   <?php
$array=array(
array("no"=>"1","subtitle"=>"Perbekalan", "title"=>"lombok ijo"),
array("no"=>"11","subtitle"=>"Perbekalan", "title"=>"lombok asdf"),
array("no"=>"2","subtitle"=>"Perbekalan", "title"=>"bawang abang"),
array("no"=>"3","subtitle"=>"Inventaris", "title"=>"Wajan")
);
echo "<pre>";
//print_r($array);
$Perbekalan=array();
$Inventaris=array();
$i=0;
foreach ($array as $value) {
    if($value['subtitle']=="Perbekalan")
    {
        $Perbekalan[$i]['no']=$value['no'];
        $Perbekalan[$i]['subtitle']=$value['subtitle'];
        $Perbekalan[$i]['title']=$value['title'];
    }
    if($value['subtitle']=="Inventaris")
    {
        $Inventaris[$i]['no']=$value['no'];
        $Inventaris[$i]['subtitle']=$value['subtitle'];
        $Inventaris[$i]['title']=$value['title'];
    }
    $i++;

}
echo "per";
print_r($Perbekalan);
echo "ins";
print_r($Inventaris);
?>

0
投票
<?php
$items=
array(
    array('no'=>"1", 'subtitle'=>"Perbekalan", 'title'=>"lombok ijo"),
    array('no'=>"3",'subtitle'=>"Inventaris", 'title'=>"Wajan"),
    array('no'=>"2",'subtitle'=>"Perbekalan", 'title'=>"bawang abang")
);

foreach($items as $item)
    $output[$item['subtitle']][] = $item;

extract($output);

var_export($Perbekalan);
echo "\n";
var_export($Inventaris);

输出:

array (
    0 => 
    array (
      'no' => '1',
      'subtitle' => 'Perbekalan',
      'title' => 'lombok ijo',
    ),
    1 => 
    array (
      'no' => '2',
      'subtitle' => 'Perbekalan',
      'title' => 'bawang abang',
    ),
  )
  array (
    0 => 
    array (
      'no' => '3',
      'subtitle' => 'Inventaris',
      'title' => 'Wajan',
    ),
  )
© www.soinside.com 2019 - 2024. All rights reserved.