2017-02-22 5 views
0

Ich mag dieses json Array bin Parsen und ich möchte type Objekt nehmen und die in New Spalte type2 Put und Dies ist eine Reihe meiner json Reihen, Warum bekomme ich diese Warnung für einige Zeilen?Warning: Invalid argument supplied for foreach() in C:\wamp64\www\json\json.php on line 18Parsing Array und Objekt json Via PHP - Invalid argument geliefert

[{"id":"26","answer":[{"option":"3","text":"HIGH"}],"type":"3"}, 
{"id":"30","answer":[{"option":"3","text":"LOW"}],"type":"3"}, 
{"id":"31","answer":[{"option":"3","text":"LOW"}],"type":"3"}] 

und dies ist mein Code:

<?php 
$con=mysqli_connect("localhost","root","","array"); 
mysqli_set_charset($con,"utf8"); 

// Check connection 
if (mysqli_connect_errno()){ 
    echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
    } 

$sql="SELECT `survey_answers`,us_id FROM `user_survey_start`"; 
if ($result=mysqli_query($con,$sql)){ 
    while ($row = mysqli_fetch_row($result)){ 
     $json = $row[0]; 
     if(!is_null($json)){ 
      $jason_array = json_decode($json,true); 
      // type2 
      $type = array(); 
      foreach ($jason_array as $data) { 
       if (array_key_exists('type', $data)) { 
        // Now we will only use it if it actually exists 
        $type[] = $data['type']; 
       } 
      }   
      // lets check first your $types variable has value or not? 
      if(!empty($type)) { 
      $types= implode(',',$type); /// implode yes if you got values 
      } 
      else { 
       $types = ''; //blank if not have any values 
      } 
      $sql2="update user_survey_start set type2='$types' where us_id=".$row[1];//run update sql 
      echo $sql2."<br>"; 
      mysqli_query($con,$sql2); 
     } 
    } 
} 
mysqli_close($con); 
?> 

Des Strang ist, warum einige Zeilen haben Output und einige Zeilen haben keine Ausgabe, Der Json Typ ist selber. Ich finde das Problem, weil einige JSON eingegeben, ich meine. Dieser hat Warning: Invalid argument supplied for foreach()

[{"id":"26","answer":[{"option":"4","text":"Hello 
"}],"type":"3"}] 

und dieses ist Okey

[{"id":"26","answer":[{"option":"4","text":"Hello"}],"type":"3"}] 

Wie kann ich das Problem beheben?

Antwort

1

Sie auch versuchen, is_array vor Ihrer für jede Schleife

if (is_array($jason_array)) 
{ 
    foreach ($jason_array as $data) { 
    { 
     ... 
    } 
} 
+0

Jaaa, gelöst, es Appriciate. –

+0

Ich habe keinen Fehler, aber in der Ausgabe habe ich keinen Wert für diese Zeilen 'Type' Too, ich meine, ich habe update user_survey_start set type2 = '' wo us_id = 267593 –

+0

ich denke, Ihre Variable $ jason_array ist kein Array that'why keine Ausgabe –

Verwandte Themen