【问题标题】:how do I set keys for JSONObjects in PHP如何在 PHP 中为 JSONObjects 设置键
【发布时间】:2014-11-23 23:26:42
【问题描述】:

简短描述:我查询我的PHP 后端,它从SQL 数据库返回数据行,数据以JSON 格式返回。数据包括每行图像的链接,以便能够创建占位符我还通过读取 32KB 图像数据来确定图像的宽度和高度,使用 webarto's answer here 中的“游侠”功能,然后附加将此数据发送到我生成的JSONArray

这是我的代码:

                    $result = $conn->query ( $sql );
                    $response = array ();
                    if ($result->num_rows > 0) {
                        while ( $row = $result->fetch_assoc () ) {
                            /* get image url */
                            $url = $row ['image'];
                            /* get the first 32KB of image data */
                            $raw = ranger ( $url );
                            /* recreate a part of the original image */
                            $im = imagecreatefromstring ( $raw );
                            /* determine width and height of the image */
                            $width = imagesx ( $im );
                            $height = imagesy ( $im );
                            /* add width and height at the end of the array */
                            array_push ( $row, $width );
                            array_push ( $row, $height );
                            $response [] = $row;
                        }
                        $j_result = json_encode ( $response );
                        echo $j_result;

其中一行的结果如下:

 {"lang":"de","title":"Sample Title","article":"Sample text","time":"1416070535","image":"someimage.jpg","source":"sample.com","0":606,"1":379}

我对@9​​87654330@ 不是很熟悉,并设法使用array_push() 函数附加图像尺寸。但是,这给了我“0”、“1”等作为这些值的键,正如您在上面的 JSON 中看到的那样。

问题:如何设置这些键,使json_encode 不会自动设置它们?

【问题讨论】:

  • Decode将json转换成PHP数组,修改后再encode再次

标签: php


【解决方案1】:

不用array_push,你可以直接使用你想要的索引:

$row['width'] = $width;
$row['height'] = $height;

【讨论】:

  • @Droidman 你没有得到我的回答?哪一部分不清楚,所以我可以尝试重新制定?
  • 我的意思是很遗憾我没有自己管理它 =) 再次感谢
【解决方案2】:

json_encode 实际上并没有设置您的 JSON 对象的任何索引,您是在 PHP 中这样做的。 json_encode 只是获取您提供的结构,并将其转换为有效 JSON 格式的字符串(如果可能)。

您需要做的不是使用array_push($row, $width),而是按照以下方式执行操作:$row['width'] = $width;$height 也是如此。然后你的$row 数组将拥有指向变量$width 的键width,并且json_encode 会对其进行适当的编码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 2011-04-11
    • 2017-08-14
    • 2014-05-06
    • 2012-11-26
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多