【问题标题】:Why isn't my multidimensional array correctly initialized and/or returned?为什么我的多维数组没有正确初始化和/或返回?
【发布时间】:2018-07-02 19:55:09
【问题描述】:

我遇到以下问题: 我有这个函数,我将查询结果($matches_lines)作为参数传递。在我的函数中,我从查询结果中获取了我需要的所有数据,并且我试图将它存储在一个多维数组中。我的代码如下:

function check_matches($matches_lines, $minage, $maxage, $actual_persontype){

    $result = array(array());
    $count = 0;

    foreach($matches_lines as $lines){

        $match_user = $lines["signup_username"];
        $match_birth = $lines["signup_birth"];
        $match_city = $lines["signup_city"];
        $match_gender = $lines["signup_gender"];
        $match_os = $lines["signup_os"];
        $match_persontype = $lines["signup_persontype"];

        if("some condition I want to verify"){

            $new_add = array($match_user, $match_birth, $match_city, $match_gender, $match_os, $match_persontype);
            array_push($result[$count], $new_add);
            $count = $count+1;  
        }
    }
    return $result;
} 

我只是简单地调用我的函数:

$matches_found = check_matches($matches_lines, $minage, $maxage, $actual_persontype);

这样做不会出错,但是当我尝试回显一行时

echo $matches_found[0][0];

我收到“HP 通知:未定义偏移量:0”。

我做错了什么?

编辑:var_dump($matches_found) 返回 "array(0) { }"

当 var_dump($matches_lines) 返回时

object(PDOStatement)#3 (1) { ["queryString"]=> string(277) "SELECT s.signup_username, s.signup_birth, s.signup_city, s.signup_gender, s.signup_os, s.signup_persontype FROM 注册 WHERE s.signup_username 'leonardo' && s.signup_city = 'Torino' && s.signup_os = 'Windows'" }

【问题讨论】:

  • 另外,如果您不能给我们条件,请再次检查条件是否真的至少匹配一行。如果你能提供,请提供。
  • array_push 通过引用获取其第一个参数(一个数组)。 $result[$count]$count = 0 之后是未定义的(null),所以它不起作用。您不能将项目推送到 null 上。

标签: php mysql sql arrays multidimensional-array


【解决方案1】:

您的代码的问题肯定在于您的条件。它不匹配任何行,因此结果不包含内部数组的值。 如果没有匹配项,您的结果将如下所示:

$matches_found = [
    0 => [/*This array does not contain an index 0, because it is empty*/]
];

因此调用$matches_found[0][0] 会为第二个0 引发错误,因为内部数组是空的。

由于您没有提供条件,我们无法帮助您修复它。

我可以说这是错误的原因是,条件后面的代码包含错误,而您说我没有收到错误。因此它永远不会被执行。

array_push($result[$count], $new_add) 行期望第一个参数$result[$count] 是一个数组。第一次迭代也是如此,因为您将 $result 初始化为 [[]]。对于 $count = 1 的第二次调用,$result 中将没有索引为 1 的字段。因此,您将收到“未定义偏移量:1”错误或“function array_push 期望参数 1 为数组类型。给定 null”错误。

这可以通过使用原生 PHP 处理将值附加到数组来解决:

$result[] = [$new_add];

$result[] = 将处理新元素的追加,[$new_add] 是一个包含一个元素的数组,即新行。如果您不需要将其包装在一个额外的数组中($new_add 本身已经是一个数组),您可以省略它周围的括号。

请注意,为了让这项工作正常工作,您必须使用$result = []; 而不是$result = [[]];(或array() 而不是array(array()))初始化$result

PHP 将自己处理新索引。您可以删除 $count 变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2017-09-13
    相关资源
    最近更新 更多