json_decode()函数什么也没有返回

时间:2018-03-18 08:44:15

标签: php mysql arrays json

我正在尝试将json数据检索到php数组中,并在foreach()循环中给出错误 Json Data如下所示:

{"_id":{"$oid":"59043fcee557e6ad53662ed5"},"url":"http://farm3.staticflickr.com/2893/34203321321_f9a2ff200b_b.jpg","asc":0,"id":1}
{"_id":{"$oid":"59043fcee557e6ad53662ed6"},"url":"http://farm3.staticflickr.com/2840/34175955132_ab92628fb3_b.jpg","asc":1,"id":1}

我用过的代码:

$file="jsonfile.json";
$jsondata=file_get_contents($file);
$data=json_decode($jsondata,true);
print_r ($data);
foreach($data as $row){
$insql ="INSERT INTO mysqltable(Nurl,Nid,sort) 
VALUES('".$row["url"]."','".$row["id"]."','".$row["asc"]."')";
echo "$insql";
mysql_query($dbconnect,$insql);
print_r ($data);
}

上面给我回复了以下错误: 任何帮助将受到高度赞赏。

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\a\json\index2.php on line 15

2 个答案:

答案 0 :(得分:1)

您必须用[]括起数据才能生成数组。并将2 json与,分开。像:

jsonfile.json

[
  {"_id":{"$oid":"59043fcee557e6ad53662ed5"},"url":"http://farm3.staticflickr.com/2893/34203321321_f9a2ff200b_b.jpg","asc":0,"id":1},
  {"_id":{"$oid":"59043fcee557e6ad53662ed6"},"url":"http://farm3.staticflickr.com/2840/34175955132_ab92628fb3_b.jpg","asc":1,"id":1}
]

php文件

$jsondata=file_get_contents($file);
$data=json_decode($jsondata,true);

echo "<pre>";
print_r( $data );
echo "</pre>";

这将导致:

Array
(
    [0] => Array
        (
            [_id] => Array
                (
                    [$oid] => 59043fcee557e6ad53662ed5
                )

            [url] => http://farm3.staticflickr.com/2893/34203321321_f9a2ff200b_b.jpg
            [asc] => 0
            [id] => 1
        )

    [1] => Array
        (
            [_id] => Array
                (
                    [$oid] => 59043fcee557e6ad53662ed6
                )

            [url] => http://farm3.staticflickr.com/2840/34175955132_ab92628fb3_b.jpg
            [asc] => 1
            [id] => 1
        )

)

答案 1 :(得分:0)

根据上面的评论 - 它是无效的json,更多的是可以正确解析的字符串集合。直接在sql中嵌入变量使得这可能容易受到sql注入的影响,如果有任何形式的用户交互,但如果数据本身包含单引号也可能会很麻烦。那就是说你可以像这样处理文件 - 尽管我建议将<?xml version="1.0" encoding="utf-8"?> <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="300.000000dp" android:height="137.000000dp" android:viewportWidth="300.000000" android:viewportHeight="137.000000"> <group android:translateY="137.000000" android:scaleX="0.100000" android:scaleY="-0.100000"> <path android:fillColor="#ff0000" android:strokeWidth="1" android:pathData="M2985 1328 c-38 -250 -110 -449 -230 -634 -221 -340 -558 -571 -965 -660 -68 -15 -127 -19 -295 -19 -168 0 -227 4 -295 19 -620 136 -1073 603 -1184 1221 -13 73 -14 25 -15 -587 l-1 -668 1500 0 1500 0 0 685 c0 377 -2 685 -4 685 -2 0 -7 -19 -11 -42z" /> </group> prepared statementmysqli一起使用。

PDO api已经被弃用了很长一段时间,所以你真的应该改成mysqli或PDO!

mysql
相关问题