Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP JSON编码-手动分配密钥?_Php_Json - Fatal编程技术网

PHP JSON编码-手动分配密钥?

PHP JSON编码-手动分配密钥?,php,json,Php,Json,我试图在AJAX请求中将MySQL查询结果转换为JSON。 我的代码现在看起来像这样 $offset = empty($_GET['offset']) ? 0 : $_GET['offset']; $numimagestodisplay = 3; $items = array(); $allitems // This is the queryset obtained through a call to a fun

我试图在AJAX请求中将MySQL查询结果转换为JSON。 我的代码现在看起来像这样

$offset              = empty($_GET['offset'])   ? 0 : $_GET['offset'];
$numimagestodisplay = 3;    
$items              = array();
$allitems           // This is the queryset obtained through a call to a function

foreach ($allitems as $i => &$item)
{
    if (($i >= $offset) && (count($items) < $numimagestodisplay))
    {
        $items[$i] = $item;
    }       
}

$output = '{"items":'.json_encode($items).'}'; 
致:

然后我可以通过键引用它,但是键显然只是0、1、2,而我需要键是循环中定义的值

如何更改PHP代码以正确的格式返回JSON

谢谢你的建议


谢谢

问题在于Javascript(以及大多数其他语言)中的数组不能有用户定义的键。您希望将数组编码为JSON对象,而不是数组(PHP中带有用户定义键的数组本质上是对象)。对于具有非数字键的数组,这通常会自动发生

在您的情况下,可以使用
JSON\u FORCE\u对象
标志:

$output = '{"items":'.json_encode($items,JSON_FORCE_OBJECT).'}';
从:


是否可以包含不正确的JSON输出?
$items[] = $item;
$output = '{"items":'.json_encode($items,JSON_FORCE_OBJECT).'}';
Non-associative array output as array: [[1,2,3]] 
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}