简体   繁体   English

如何在PHP中删除JSON周围的方括号

[英]How to remove the square brackets around a JSON in PHP

How can I have the php script return json without the square brackets? 我怎样才能让PHP脚本不带方括号返回json? I am also getting the INT values back with double quotes for some reason. 由于某种原因,我也用双引号使INT值返回。 Is it possible to remove those as well? 是否可以将其删除?

What I am getting now: 我现在得到的是:

[{"id":"1","name":"Jack","username":"Jack1","age":"23"}]

What I would like: 我想要的是:

{"id": 1,"name":"Jack","username":"Jack1","age":23}

The following is the php script that returns the JSON: 以下是返回JSON的php脚本:

<?php

$con = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT username, name FROM DriverInfo WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql)) {
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    while ($row = $result->fetch_object()) {
        // Add each row into our results array
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    // Finally, encode the array to JSON and output the results
    echo json_encode($resultArray);
}

mysqli_close($con);

You are building an array of the resulting rows from your mysql query. 您正在从mysql查询中生成结果行的数组。 The square brackets are there because that is the notation for an array in JSON. 方括号在这里是因为这是JSON中数组的表示法。 It looks like you only want to return the first row, so you don't need that while statement: 看来您只想返回第一行,所以您不需要while语句:

$row = $result->fetch_object();
if ($row) {
    echo json_encode($row);
} else {
    echo '{}';
}

Also you'll want to be aware of this: How can I prevent SQL injection in PHP? 另外,您还需要注意以下几点如何防止PHP中的SQL注入?

The square brackets indicate that your variable originated from an array of objects, and is expected for translating it back to the original value. 方括号表示您的变量源自对象数组,应该将其转换回原始值。

However, you can use a combination of JSON_* constants for the options argument, such as JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK 但是,您可以将JSON_*常量组合用于options参数,例如JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK , to ensure your desired result from json_encode . JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK ,以确保从json_encode所需的结果。

  • JSON_NUMERIC_CHECK will remove the double quotes from the numeric values in your JSON string. JSON_NUMERIC_CHECK将从JSON字符串中的数字值中删除双引号。
  • JSON_FORCE_OBJECT will convert all arrays into objects. JSON_FORCE_OBJECT将所有数组转换为对象。

To remove the square brackets, if your $resultArray variable is an array of objects, you will need to determine which value you want. 要删除方括号,如果$resultArray变量是对象数组,则需要确定所需的值。 Such as $resultArray[0] or end($resultArray) or reset($resultArray) 例如$resultArray[0]end($resultArray)reset($resultArray)

Example: https://3v4l.org/ip6GN 例如: https//3v4l.org/ip6GN

echo json_encode(reset($resultArray), JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);

Result: 结果:

{"id":1,"name":"Jack","username":"Jack1","age":23}

However in this instance you are looking for a specific record in the database. 但是,在这种情况下,您正在数据库中寻找特定记录。 Assuming there is only one, I suggest updating your query to leverage a prepared statement , to avoid SQL injection attacks. 假设只有一个,我建议您更新查询以利用准备好的语句 ,以避免SQL注入攻击。

Additionally I highly recommend hashing your passwords using the built in password_hash functions. 另外,我强烈建议您使用内置的password_hash函数对您的密码进行哈希处理。

$sql = 'SELECT `id`, `username`, `name`, `age` 
FROM `DriverInfo` 
WHERE `username` = ? 
AND `password` = ? 
LIMIT 1';
$stmt = mysqli_stmt_init($con);
if (mysqli_stmt_prepare($stmt, $sql)) {
    mysqli_stmt_bind_param($stmt, 'ss', $username, $password);
    $username = $_POST['username'];
    $password = $_POST['password'];
    mysqli_stmt_execute($stmt);
    if ($result = mysqli_stmt_get_result($stmt)) {
       if ($row = mysqli_fetch_object($result)) {
           echo json_encode($row, JSON_FORCE_OBJECT | JSON_NUMERIC_CHECK);
       }
    }
}
mysqli_stmt_close($stmt);
mysqli_close($con);

The json you want is in a single element php array, so try doing echo json_encode($resultArray[0]) . 您想要的json位于单个元素php数组中,因此请尝试执行echo json_encode($resultArray[0]) Also if you're expecting an int back and you know where, just use parseInt() in your javascript when handling the response 另外,如果您期望返回int并且知道在哪里,则在处理响应时只需在JavaScript中使用parseInt()

Finally, encode the array to JSON and output the results 最后,将数组编码为JSON并输出结果

echo json_encode(array("data"=>$resultArray));

output: 输出:

data:[{"id":1,"name":"Jack","username":"Jack1","age":23}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM