2016-07-25 64 views
-1

我試圖改變JSON文件中的值。我想從'Merchant'鍵的項目中刪除點之後的部分字符串。例如,應將「Amazon.com」替換爲「Amazon」。用php編輯並保存Json

這裏是我的代碼:

$file = 'myfile.json'; 
$jsonString = file_get_contents($file); 
$data = json_decode($jsonString, true); 
foreach ($data as $key => $field){ 
    $data[$key]['Merchant'] = (explode(".",$data[$key]['Merchant'])); 
} 
$newJSON = json_encode($data); 
file_put_contents($file, $newJSON); 

這裏是我的JSON文件:(我想以後取代一切[點])

[ 
    { 
     "0": { 
      "Code": "No Voucher Code",     
      "Merchant": "Amazon.com",    
      "Title": "Upto 70% off on Toys, Kids Apparel and Stationary" 

     }, 
     "1": { 
      "Code": "No Voucher Code", 
      "Merchant": "ebay.com",    
      "Title": "Set of 3 LED Bulbs @ Rs. 99 + Free Shipping"     
     } 

輸出:節約和替代商人價值

[ 
    { 
     "0": { 
      "Code": "No Voucher Code",     
      "Merchant": "Amazon",    
      "Title": "Upto 70% off on Toys, Kids Apparel and Stationary" 

     }, 
     "1": { 
      "Code": "No Voucher Code", 
      "Merchant": "ebay",    
      "Title": "Set of 3 LED Bulbs @ Rs. 99 + Free Shipping"     
     } 

但是我的代碼並沒有改變"Merchant"的值。爲什麼不?

+1

究竟如何不工作的代碼? –

回答

0

您的JSON位於您未尋址的外部數組中。您需要循環使用$data[0]而不是$data。您可以更簡單地使用參考來做到這一點。在循環中,利用explode後,將第一個爆炸元素回'Merchant'鍵:

foreach ($data[0] as &$field){ 
    $field['Merchant'] = explode(".",$field['Merchant'])[0]; 
} 
unset($field); // unset the reference to avoid weirdness if $field is used later 
1

使用帶有json_decodestrstr功能如下方法(我已經採取了從字符串演示一個JSON數據):

$jsonString = '[ 
    { 
     "0": { 
      "Code": "No Voucher Code",     
      "Merchant": "Amazon.com",    
      "Title": "Upto 70% off on Toys, Kids Apparel and Stationary" 

     }, 
     "1": { 
      "Code": "No Voucher Code", 
      "Merchant": "ebay.com",    
      "Title": "Set of 3 LED Bulbs @ Rs. 99 + Free Shipping"     
     } 
    } 
]'; 

$data = json_decode($jsonString, true); 

foreach ($data[0] as $key => &$v) { 
    $v['Merchant'] = strstr($v['Merchant'], ".", true); 
} 
$newJSON = json_encode($data, JSON_PRETTY_PRINT); 

print_r($newJSON); 

DEMO link

+0

我同意'strstr'似乎更適合這個。 –