2016-07-25 71 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'似乎更适合这个。 –