PHP 重复循环,直到没有匹配的记录

标签 php mysql arrays loops reference

我有一张表,其中包含:

TICKET  | VOLUME | REFF
------------------------
111111  | 1      | 
111112  | 0.5    | 111111
111113  | 2      | 
111114  | 1      | 111112
111115  | 4      | 111114
111116  | 2      | 111113
111117  | 1      | 111116
and so on..

我想显示的结果(以数组格式)是:

[
    [ 'TICKET' => 111112, 'VOLUME' => 0.5 ],
    [ 'TICKET' => 111114, 'VOLUME' => 1 ],
    [ 'TICKET' => 111115, 'VOLUME' => 4 ]
]

所以,所有的答案都与票号有关。 11111。 怎么做?

非常感谢!

到目前为止我已经尝试过:

$parent_ticket = 111111;
$res = [];

   $cek = DB::table('data_ticket')->where('ticket', $parent_ticket)->first();

   if($cek){
       $cek_child1 = DB::table('data_ticket')->where('ticket', $cek->REFF)->first();

       if($cek_child1){
          $res[] = [ 'TICKET' => $cek_child1->TICKET, 'VOLUME' => $cek_child1->VOLUME ];
          $cek_child2 = DB::table('data_ticket')->where('ticket', $cek_child1->REFF)->first();

          if($cek_child2){
             $res[] = [ 'TICKET' => $cek_child2->TICKET, 'VOLUME' => $cek_child2->VOLUME ];
             $cek_child3 = DB::table('data_ticket')->where('ticket', $cek_child2->REFF)->first();

             if($cek_child3){
                // and so on....
             }

          }
       }
   }

最佳答案

您应该使用递归,这是完成您想要的操作的最简单方法。

<?php

$parent_ticket = 111111;
$res = [];

$cek = DB::table('data_ticket')->where('ticket', $parent_ticket)->first();

if ($cek) {
    findAllTicketsAndReferences($cek, $res);
}

function findAllTicketsAndReferences($cek, array &$res)
{
    $cek_child1 = DB::table('data_ticket')->where('ticket', $cek->REF)->first();

    if (!$cek_child1) {
        return false;
    }

    $res[] = ['TICKET' => $cek_child1->TICKET, 'VOLUME' => $cek_child1->VOLUME];

    findAllTicketsAndReferences($cek_child1, $res);
}

这应该可行,想法是当不再有子项时返回 false,否则它会继续并更改数据数组。

关于PHP 重复循环,直到没有匹配的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45343920/

相关文章:

php - 比较php中的数组值

javascript - CodeIgniter 在菜单上添加一个子文件夹作为链接

PHP session 数组 - 存储具有不同值的相同项目

asp.net - 旧站点迁移选项

java - 如何使用 hibernate JPA 注释连接两列

java - 为什么我的数组值在回收器 View 中不起作用

c++ - 在 C++ 中声明二维指针数组的方法

php - Ajax 读取数据库

php - WordPress 错误 "A variable mismatch has been detected."

php - UTF8 正确的文本但保存不正确