使用数组的PHP问题编码JSON [英] Encoding JSON with PHP issues with array

查看:105
本文介绍了使用数组的PHP问题编码JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个简单的问题..我正在尝试使用传单实时库,但它需要加载特定的JSON输出,例如:

this is a simple question.. I'm trying to use leaflet realtime library, but it requires to load a specific JSON output such as:

data: {"type":"Feature","geometry":{"type":"Point","coordinates":[-85.26995166666667,35.056891]},"properties":{"color":"#FFFFFF","route":"U"},"id":"118"}

到目前为止,这就是我所得到的:

so far this is all I got:

[{"type":"Feature","coordinates":["-34.66159","-59.42428"],"color":"#FFFFFF","route":"u", id:118}]

这是我的PHP

    $id=$row['id'];
    $type=$row['type'];
    $lat=$row['lat'];
    $lng=$row['lng'];
    $color=$row['color'];
    $route=$row['route'];




    $data [] = array('id'=> $id, 'type'=> $type,'coordinates'=> $lnglat = array ($lat, $lng),
                        'colour'=> $colour, 'route'=> $route);

$json_string = json_encode($data);
echo $json_string;

这太疯狂了……我尝试了一切..我读了很多json_encode教程..但是我找不到像我这样的例子或情况.

This is driving crazy... I tried everything.. I read lots of json_encode tutorial..but I can't find an example or situation such as mine.

请帮助!

谢谢!

推荐答案

尝试对您需要创建的json进行解码,以查看PHP数据结构应如何:

Try to decode the json you need to create to see how the PHP data structure should look like:

$json='{"type":"Feature","geometry":{"type":"Point","coordinates":[-85.26995166666667,35.056891]},"properties":{"color":"#FFFFFF","route":"U"},"id":"118"}';
$data = json_decode($json, TRUE);
print_r($data);

输出为:

Array
(
    [type] => Feature
    [geometry] => Array
        (
            [type] => Point
            [coordinates] => Array
                (
                    [0] => -85.269951666667
                    [1] => 35.056891
                )
        )
    [properties] => Array
        (
            [color] => #FFFFFF
            [route] => U
        )
    [id] => 118
)

现在,您的代码应如下所示:

Now, your code should look like:

$data = array(
    'type' => $type,
    'geometry' => array(
        'type' => 'Point',
        'coordinates' => array($lat, $lng),
    ),
    'properties' => array(
        'color' => $color,
        'route' => $route,
    ),
    'id' => $id,
);
echo(json_encode($data));

更新:作为@ paul-crovella在评论中的评论,在代码的第一段中使用var_export()代替print_r()可以直接生成与上面显示的代码非常相似的PHP代码(除了可以复制粘贴到您的代码中并通过将值('Features'35.056891'#FFFFFF' aso)替换为相应的变量($type$lng等).

UPDATE: as @paul-crovella remarks in a comment, using var_export() instead of print_r() in the first fragment of code produces directly PHP code very similar with the one displayed above (except for the variables/values) that can be copy-pasted into your code and used by replacing the values ('Features', 35.056891, '#FFFFFF' a.s.o.) with the corresponding variables ($type, $lng, $color etc).

这篇关于使用数组的PHP问题编码JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆