如何在PHP中设置JSONObjects的密钥

问题描述:

简短描述:我查询我的PHP后端,该后端从SQL数据库返回数据行,数据以JSON格式返回。这些数据包含了每行图像的链接,为了能够创建占位符,我还通过读取32KB图像数据,使用“范围”功能按照webarto's answer here确定图像的宽度和高度,然后附加此数据到我的结果JSONArray如何在PHP中设置JSONObjects的密钥

这是我的代码有:

    $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} 

我不是很熟悉PHP和管理,以追加图像尺寸使用array_push()函数。但是,如上面的JSON所示,这给了我“0”,“1”等作为这些值的关键字。

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

+0

[解码](http://php.net/manual/en/function.json-decode.php)的JSON到一个PHP数组,修改它然后[编码](http://php.net/manual/en/function.json-encode.php)它再次 – Bankzilla 2014-11-23 23:29:14

而不是使用array_push,你可以简单地使用索引要直接:

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

谢谢,这是一种遗憾,我没有得到它 – Droidman 2014-11-23 23:37:07

+0

@Droidman你没有得到我的答案?什么部分不清楚,所以我可以尝试重新制定? – DanielX2010 2014-11-23 23:38:31

+0

我的意思是这是一个耻辱我没有管理它我自己=)再次感谢 – Droidman 2014-11-23 23:43:27

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

你需要做的是代替使用array_push($row, $width),按照$row['width'] = $width;$height的顺序做一些事情。然后,您的$row阵列将具有指向变量$width的密钥width,并且json_encode将对其进行适当的编码。