2016-08-25 71 views
0

我在mysql數據庫表中使用json格式的數據,如下所述。如何在php中使用str_replace函數替換數組中的值

{ 
"dataType": "mis_type", 
"diceCode": "20070100102", 
"forms": { 
    "4. Campus": {}, 
    "7. Classroom": {}, 
    "1. Details of school": { 
      "School_Name": "GOVT. UPG .M.S. KHAGARA", 
      "Village_Name": "KHAGARA", 
      "Block_Name": "MOHAN PUR", 
      "Dist_Name": "DEOGHAR", 
      "Type_of_School": "DEPARTMENT OF EDUCATION", 
      "Category": "PRIMARY WITH UPPER PRIMARY", 
      "No_of_Student": 209, 
      "No_of_Section": 8, 
      "No_of_Classroom": 5, 
      "Govt_Teacher": 2, 
      "Para_Teacher": 3, 
      "Other_Teacher": 0, 
      "Total_Teacher": 5, 
      "Total_Toilet": 2, 
      "Total_Urinals": 2 
      }, 
    "6. Drinking Water Source": {}, 
    "8. Kitchen Shed": {}, 
    "2. Location of School": {}, 
    "5. Location of Toilet": {}, 
    "3. Pollution Status": { 
    } 
    } 
} 

我想從另一個新值中替換「Total_Toilet」值。爲此我寫了下面的代碼。

$selectQuery = "SELECT `json_data` FROM `abc` WHERE `disc_code`='" . $diseCode . "' AND `type`='mis'"; 
    $res = $conn->query($selectQuery); 
    $jsonvalue = $res->fetch_assoc(); 
    $jsonvalue = json_decode($jsonvalue['json_data'], true); 
    unset($value['Dise_Code']); 
    unset($value['OBJECTID']); 
    if ($res->num_rows > 0) 
{ 
    foreach($jsonvalue['forms']['1. Details of school'] as $key1 => $value1) 
{ 
    echo"<br>"; 
    $key2 = str_replace($jsonvalue['forms']['1. Details of school'] ['Total_Toilet'] , 4, $value1) ; 
    echo $key2; 
} 

的代碼被編譯沒有任何錯誤,但仍然是以前的值是沒有得到使用str_replace函數功能的新值替換。 如果有什麼問題我正在做,那麼請指導我,或者如果有任何替代解決方案的人知道請幫助我。

任何幫助,將不勝感激。

+0

foreach中的$ value1的值是什麼 – LOKESH

+0

以及您需要什麼作爲輸出? – LOKESH

+0

我正在$ value1變量中獲取「School of Details」對象的所有值。您可以在json中看到的值,如上所示。 –

回答

1

好吧,請在下面添加行foreach循環

$jsonvalue['forms']['1. Details of school']['Total_Toilet'] = 4; 

之前,使foreach循環如下

foreach($jsonvalue['forms']['1. Details of school'] as $key1 => $value1) 
{ 
    echo"<br>"; 
    $key2 = $value1; 
    echo $key2; 
} 

我希望這會幫助你。

+0

感謝您的評論...錯誤我發佈語法錯誤我使用相同,如你所建議的。 –

+0

即使它不工作? – Mahamadali

+0

是的......它沒有在我的代碼中出現這個語法錯誤。 –

0

請如下改變你的foreach循環來更新數據庫

foreach($jsonvalue['forms']['1. Details of school'] as $key1 => $value1) 
{ 
    $current_value = $jsonvalue['forms']['1. Details of school']['Total_Toilet']; 
    $new_value = '12'; // Replace with new value that you want 
    echo $new_json = str_replace('"Total_Toilet": '.$current_value.'','"Total_Toilet": '.$new_value.'',$jsonvalue['json_data']); 
    echo "<hr>"; 
    $updateQuery = "update `abc` set `json_data` = '".$new_json."' WHERE `disc_code`='" . $diseCode . "' AND `type`='mis'"; 
    $res = $conn->query($updateQuery); 
} 

注:編輯在查詢中的變量按你的requirements.Feel自由評論。