PHP递归函数返回数组结果

时间:2019-01-25 09:30:41

标签: php

我在理解PHP中的递归函数时遇到问题。

我想从旧ID(服务)开始检索所有更新旧服务的服务。返回数组结果。

例如我的表格“服务”

ID  | Name  | DateExpire  |IDOldServiceRenewed|
-----------------------------------------------
1   | Serv1 | 2018-10-10  |                   |
-----------------------------------------------

2   | Serv2 | 2018-10-11  |                   |
-----------------------------------------------

3   | Serv3 | 2018-10-12  |         2         |
-----------------------------------------------

4   | Serv4 | 2018-10-13  |         3         |
-----------------------------------------------

5   | Serv5 | 2018-10-14  |         1         |
-----------------------------------------------

6   | Serv6 | 2018-10-15  |                   |
-----------------------------------------------

7   | Serv7 | 2019-02-10  |        4          |
-----------------------------------------------

8   | Serv8 | 2019-05-15  |         5         |
-----------------------------------------------

因此在我的示例中,如果我想使用ID = 2来了解旧服务的所有新服务(以便从旧版本更新到新版本),我想返回这样的数组:

$result = array(
  "0" => array(
    "ID" => 3,
    "Expired" => 2018-10-12
  ),
  "1" => array(
    "ID" => 4,
    "Expired" => 2018-10-13
  ),
  "2" => array(
    "ID" => 7,
    "Expired" => 2019-02-10
  )
)

对于ID = 1

$result = array(
  "0" => array(
    "ID" => 5,
    "Expired" => 2018-10-14
  ),
  "1" => array(
    "ID" => 8,
    "Expired" => 2019-05-15
  )
)

我尝试从这样的函数开始,但是我在var_dump中总是得到NULL:

function get_recursive_id_services($idOldService, &$result) {

    $sql = "SELECT SERVICES.* FROM SERVICES WHERE IDOldServiceRenewed = ?";

    $s = $db->prepare($sql);
    $s->execute(array($idOldService));
    $ris = $s->fetch(PDO::FETCH_ASSOC);

    if ( $ris ) {

        $id= $ris['ID'];

        $result[$idOldService] = $id;

        $result[] = get_recursive_id_services($id, $result);

    } else {

        return $result;

    }

}

// TEST

$temp = array();

$result = get_recursive_id_services(2, $temp);

var_dump($result);

2 个答案:

答案 0 :(得分:2)

您的代码存在一个市长问题。您的函数将$result参数作为参考。这意味着该行:

$result[] = get_recursive_id_services($id, $result);

将给出类似的内容:

array(
    1 => array( "id" => ... , "expired" => ...),
    2 => array( 1 => array( "id" => ... , "expired" => ...) )
)

您想要的是这里:

return get_recursive_id_services($id, $result);

答案 1 :(得分:0)

由于@Karol Samborski的建议,我终于使它工作了。

function get_recursive_id_services($id, &$result) {

  $sql = "SELECT SERVICES.* FROM SERVICES WHERE IDOldServiceRenewed = ?";
  $s = $db->prepare($sql);
  $s->execute(array($id));
  $ris = $s->fetch(PDO::FETCH_ASSOC);
  if ( $ris ) {
    $idNewService = $ris['ID'];
    $result[] = array("ID" => $idNewService, "DateExpire" => $ris['DateExpire']);
    return get_recursive_id_services($idNewService, $result);
  } else {
    return $result;
  }

}