2015-09-07 70 views
-1

我JSON像这样(从嵌套排序)我怎样才能把JSON到MySQL和PHP循环?

[ 
{"id":13},{"id":14}, 
{"id":15, 
    "children":[ 
      {"id":16},{"id":17},{"id":18} 
    ] 
}, 
{"id":19},{"id":20}, 
{"id":21, 
     "children":[ 
      {"id":22} 
     ] 
} 
] 

如何我PHP循环把这个JSON在MySQL

谢谢。

回答

0

与任何有效的JSON格式字符串一样,您可以使用PHP内置的json_decode将其转换为可解析对象,然后遍历这些参数。在这种情况下,从JSON字符串你给了(这似乎是一个数组)

$array = json_decode($string); 
foreach ($array as $val) { 
    //The object $val will be: 
    "id":13 
} 

如果它是嵌套的,你会做另一个foreach循环,并检测是否需要进行环财产。例如,你可以在多种方式(通过$val性检查的"children"财产,循环和检查它是否是一个array,如果是则循环通过)做到这一点。这里面的foreach循环迭代,你可以将其插入,或做你执行需要得到它在MySQL

你的问题是你想要它插入的格式和方式很模糊任何声明。我建议展示一些代码,你试过这样其他人可以帮助你,知道你要去哪个方向。(这可能为downvote的原因,而不是由路矿)

Looping through all the properties of object php

+0

我认为他想他的数据存储在MySQL。无法访问它。 – aldrin27

+0

我编辑我的回答告诉他,他可以访问数据,并用它在迭代'foreach'插入它(管理费用,但我不知道他想用它做什么)。感谢您的反馈! –

0

只要把你的有效的JSON内json_decode并将其分配给一个PHP数组如下

//$php_arr = json_decode('YOUR_JSON'); 
$php_arr = json_decode('[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]'); 

/*comment the following 3 lines when done*/ 
echo "<pre>"; 
print_r($php_arr); 
echo "</pre>"; 
/*comment the above 3 lines when done*/ 

输出

Array 
(
    [0] => stdClass Object 
     (
      [id] => 13 
     ) 

    [1] => stdClass Object 
     (
      [id] => 14 
     ) 

    [2] => stdClass Object 
     (
      [id] => 15 
      [children] => Array 
       (
        [0] => stdClass Object 
         (
          [id] => 16 
         ) 

        [1] => stdClass Object 
         (
          [id] => 17 
         ) 

        [2] => stdClass Object 
         (
          [id] => 18 
         ) 

       ) 

     ) 

    [3] => stdClass Object 
     (
      [id] => 19 
     ) 

    [4] => stdClass Object 
     (
      [id] => 20 
     ) 

    [5] => stdClass Object 
     (
      [id] => 21 
      [children] => Array 
       (
        [0] => stdClass Object 
         (
          [id] => 22 
         ) 

       ) 

     ) 

) 

现在你有PHP数组做什么你想要什么

foreach($php_arr as $arr){ 
    if(!isset($arr['children'])){ 
     $q = "insert into tbl(id) values('".$arr['id']."')"; 
    }else{ 
     //your logic 
    } 
} 
0

你需要使用json_decode函数来解码JSON数据。然后使用foreach循环来处理数据。

尝试例如

$str = ' 
    [{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}] 
'; 

$json = json_decode($str); 

//var_dump($json); 
foreach ($json as $item) 
{ 
    //The object $val will be: 
    echo $item->id."<br />"; 
    //You INSERT query is here 
    //echo "INSERT INTO table (field) VALUE ($item->id)"; 
    $query = mysqli_query($conn, "INSERT INTO table (field) VALUE ($val->id)"); 
}