【问题标题】:PHP Repeat loop until no matching recordPHP重复循环,直到没有匹配的记录
【发布时间】:2018-01-02 18:40:00
【问题描述】:

我有一张表,其中包含:

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....
             }

          }
       }
   }

【问题讨论】:

  • 你试过什么?
  • 如果 Ref 的条件为 null,则不执行任何其他操作,设置索引零为 TICKET 且索引 1 为 VOLUME 的两项数组
  • 我已经尝试手动搜索 10 次,如何自动进行直到没有孩子可用?
  • @Osama 感谢您的回答,我错了,我已经编辑了问题,除了父母之外没有空数据。
  • 为什么不把你试过的代码贴出来?

标签: php mysql arrays loops reference


【解决方案1】:

你应该使用递归,这是做你想做的最简单的方法。

<?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,否则它会继续并更改数据数组。

【讨论】:

  • 是的,你明白我的意思!谢谢,我会先将此标记为已接受的答案,然后再尝试。
猜你喜欢
  • 2012-03-11
  • 2016-04-28
  • 2016-03-30
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多