PHP 内爆不起作用

PHP implode not working

我正在尝试获取一个包含多行会话和页面 url 的 table,并将它们放在一个 table 中,每行包含会话和访问过的所有页面,并用 ' 分隔|'.

下面的代码只返回旁边没有 URL 的会话。关于我在这里做错了什么有什么想法吗?

<?php
$html = "<table>\n";
$html .= "<tr>\n<th>SESSION</th>\n<th>PATH</th>\n</tr>\n";
$paths = array();
$sql = "SELECT session_id, page_url FROM pageviews";
$result = mysqli_query($conn, $sql);
$got_rows = mysqli_num_rows($result);

if ($got_rows) {
    while ($row = mysqli_fetch_array($result)) {
        array_push($paths[$row['session_id']], $row['page_url']);
    }

    foreach ($paths as $session => $page) {
        $html .= "<tr>\n";
        $html .= '<td>' . $session . "</td>\n";
        $html .= '<td>' . implode('| ', $page) . "</td>\n";
        $html .= "</tr>\n";
    }

} else {
    $html .= '<td colspan="2">No results</td>' . "\n";
}

$html .= "</table>\n";
echo $html;

if (!mysqli_query($conn,$sql))  {
    die('Error: ' . mysqli_error($conn));
}

mysqli_close($conn);
?>

如果打开错误报告,您应该会收到 array_push():

的错误消息

Warning: array_push() expects parameter 1 to be array, null given

参见:3v4l.org example of error

在您的示例中,您已将数组定义为:

$paths = array();

但是,在您的 while() 中,您试图将新项目添加到不存在的数组中:

array_push($paths[$row['session_id']], $row['page_url']);
// $paths[$row['session_id']] hasn't been defined as an array, which array_push() expects

像这样应该可以解决您的问题:

while ($row = mysqli_fetch_array($result)) {

    // Create an array for the session_id if it doesn't exist yet
    if ( ! array_key_exists($row['session_id'], $paths) || ! is_array($paths[$row['session_id']])) {
        $paths[$row['session_id']] = [];
    }

    // Add to the array now that we know it exists
    array_push($paths[$row['session_id']], $row['page_url']);
}

参见:3v4l.org working example

作为旁注,您可以删除 array_push($arr, $var) 并简单地使用更快的 $arr[] = $var。来自 PHP docs:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.