【问题标题】:PHP Array sometimes returns just 'array'PHP Array 有时只返回 'array'
【发布时间】:2018-08-16 14:44:28
【问题描述】:

我想知道为什么我还没有找到任何解决这个奇怪问题的方法。 抱歉,如果我看起来不正确,但我非常绝望,并尝试尽可能多地解决这个问题。

在递归函数中,我收集 sql 数据并将它们存储在一个数组中。 但是,当我使用 print_r 输出数组值时,会得到如下奇怪的值:

a."parentMale" = '45273' 或 a."parentFemale" = '44871' 或 a."parentMale" = '7625' 或 a."parentFemale" = '7481' 或数组或数组 OR Array OR Array OR a."parentMale" = ...

虽然我的函数看起来像这样:

    public function getSelfAndAncestorsShort($id) {
  $animalids = array();
  if ($id != "") 
  {
      $query = "SELECT a.\"parentMale\" AS sire, a.\"parentFemale\" AS dam
      FROM animals a
      WHERE a.id = ".$id;

      $res = pg_query($query);
      while ($row = pg_fetch_object($res)) 
      {
        if ($row->sire != "")
        $animalids[]  = "a.\"parentMale\" = '" .$row->sire ."'";
        if ($row->dam != "")
        $animalids[]  = "a.\"parentFemale\" = '" .$row->dam ."'";

        $animalids[] = $this->getSelfAndAncestorsShort($row->sire);
        $animalids[] = $this->getSelfAndAncestorsShort($row->dam);

        $animalids = implode (" OR ", $animalids);

      }

  }
  return $animalids;
}

我希望有人可以帮助我,因为我真的不知道。

【问题讨论】:

  • 您收到一个错误,因为在其中一个结果中返回了数组并且您尝试将其作为字符串处理。您需要修复函数并检查数据类型
  • 您正在使用 implode() 将数组更改为字符串,最后您只得到字符串。

标签: php sql arrays postgresql


【解决方案1】:

如果$id 为空,您的函数将返回一个数组。此外,您在添加到 $animalids 数组之前不要检查函数的返回:

public function getSelfAndAncestorsShort($id) {
  $animalids = array();
  if ($id != "")
  {
      $query = "SELECT a.\"parentMale\" AS sire, a.\"parentFemale\" AS dam
      FROM animals a
      WHERE a.id = ".$id;

      $res = pg_query($query);
      while ($row = pg_fetch_object($res))
      {
        if ($row->sire != "")
        $animalids[]  = "a.\"parentMale\" = '" .$row->sire ."'";
        if ($row->dam != "")
        $animalids[]  = "a.\"parentFemale\" = '" .$row->dam ."'";

        $val = $this->getSelfAndAncestorsShort($row->sire);
        if ($val) $animalids[] = $val; // Check here
        $val = $this->getSelfAndAncestorsShort($row->dam);
        if ($val) $animalids[] = $val; // Check here

      }

  }
  if (empty($animalids)) return "" ; // Check here
  return implode (" OR ", $animalids); // Only implode here
}

【讨论】:

  • 非常感谢。这给了我预期的结果
猜你喜欢
  • 2018-09-17
  • 1970-01-01
  • 2020-01-15
  • 2016-10-23
  • 1970-01-01
  • 2018-01-22
  • 2010-12-23
  • 2021-08-18
  • 1970-01-01
相关资源
最近更新 更多