编辑&用PHP保存Json

时间:2016-07-25 20:01:02

标签: php arrays json

我正在尝试更改JSON文件中的值。我想删除'Merchant'项中的项后点的字符串部分。例如,“Amazon.com”应替换为“亚马逊”。

这是我的代码:

$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文件:(我想替换之后的所有内容。[dot])

[
    {
        "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"值。为什么不呢?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您的JSON位于您未寻址的外部数组中。您需要循环$data而不是$data[0]。您可以使用引用更简单地完成此操作。在循环内部,使用'Merchant'后将第一个展开的元素分配回explode键:

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