PHP数组没有正确格式化

时间:2013-04-02 23:15:55

标签: php arrays

我似乎无法弄清问题是什么,但我的PHP数组没有输出正确的JSON。我删除了json_encode函数,只是发现我的数组是级联的并且没有正确格式化自己。以下是输出示例(删除了json_encode):

Array (
    [0] => Array (
        [username] => g4m3b0y
        [profile_photo] => default.png
        [email] => michael@me.com
        [first_name] => Michael
        [last_name] => Simpson
    )
) 
Array (
    [0] => Array (
        [username] => g4m3b0y
        [profile_photo] => default.png
        [email] => michael@me.com
        [first_name] => Michael
        [last_name] => Simpson
    )
    [1] => Array (
        [username] => michelle
        [profile_photo] => default.png
        [email] => michelle@gmail.com
        [first_name] => Michelle
        [last_name] => Houston
    )
)

正如您所看到的,它在单独的数组中创建了重复的结果,因此我的JSON输出问题。这是我生成结果的代码:

    $sql2 = "SELECT DISTINCT username, profile_photo, first_name, last_name, email FROM users WHERE (
        first_name LIKE '%$q%'
        OR last_name LIKE '%$q%'
    ) ORDER BY last_name";

    $sq2 = mysql_query($sql2);
    $st2 = mysql_num_rows($sq2);

    if($st2>=1) {   
        while($a = mysql_fetch_array($sq2)) {
            $userRow[] = array(
                'username' => $a['username'],
                'profile_photo'   => $a['profile_photo'],
                'email'   => $a['email'],
                'first_name'   => $a['first_name'],
                'last_name'   => $a['last_name']
            );
        header('Content-Type: application/json');
        echo json_encode($userRow);
        }
    }

    else {
        exit;
    }

1 个答案:

答案 0 :(得分:1)

您对headerjson_encode的来电是在您的while循环中。将它移到外面,它会将批次编译成一个json字符串。目前它正在输出多个独立的。

这也解释了为什么你也得到副本。迭代1将第一行添加到数组$userRow,然后输出已获得键0的结果。然后第二次迭代将下一行添加到现有数组,因此获得键1。然后它再次回显json编码的字符串,因此这次打印0和1。因此0然后是0,然后是1

$sql2 = "SELECT DISTINCT username, profile_photo, first_name, last_name, email FROM users WHERE (
    first_name LIKE '%$q%'
    OR last_name LIKE '%$q%'
) ORDER BY last_name";

$sq2 = mysql_query($sql2);
$st2 = mysql_num_rows($sq2);

if($st2>=1) {   
    while($a = mysql_fetch_array($sq2)) {
        $userRow[] = array(
            'username' => $a['username'],
            'profile_photo'   => $a['profile_photo'],
            'email'   => $a['email'],
            'first_name'   => $a['first_name'],
            'last_name'   => $a['last_name']
        );
    }

    // I moved this below the above }
    header('Content-Type: application/json');
    echo json_encode($userRow);
}

else {
    exit;
}