如何使用php使用新值更新json数据标签的值?

时间:2018-07-09 06:56:01

标签: php json

我想使用PHP更新标签值。假设我输入相同的标签,那么如果存在相同的命名标签,它将匹配该标签,然后它将更新该标签的值。

[{
    "label": "aa",
    "val": "12"
},
{
    "label": "new",
    "val": "13"
},
{
    "label": "yy",
    "val": "14"
}]

在上面的data.json中,我想将label:“ yy”的值更新为val:“ 20”。为此,我正在使用此代码

$myFile = "data.json";
$arr_data = array(); // create empty array
try
{
    //Get form data
    $formdata = array(
        'label'=> $_POST['label'],
        'val' => $_POST['val']
    );
    //Get data from existing json file
    $jsondata = file_get_contents($myFile);
    // converts json data into array
    $arr_data = json_decode($jsondata, true);
    foreach($arr_data as $item){
    }
    // array_push($arr_data,$formdata);
    $jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
    /*this is the matching label code*/
    if(in_array($formdata['label'],$item)){
        $item['val'] = $formdata['val'];
        echo $item['val'];
        echo "got it";
    }
    else echo "not matched";
    //write json data into data.json file
    if(file_put_contents($myFile, $jsondata)) {       
    }
    else 
        echo "error";
}
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

3 个答案:

答案 0 :(得分:1)

foreach循环内移动代码以匹配标签名称,以便可以比较json数组中的每个标签值。更新的代码:

$myFile = "data.json";
try {
//Get form data
    $formdata = array(
        'label' => $_POST['label'],
        'val' => $_POST['val']
    );
    //Get data from existing json file
    $jsondata = file_get_contents($myFile);
   // converts json data into array
    $arr_data = json_decode($jsondata, true);
    foreach ($arr_data as $key => $item) {
        /* this is the matching label code */
        if ($formdata['label'] == $item["label"]) {
            $arr_data[$key]["val"] = $formdata['val'];
            echo $item['val'];
            echo "got it";
        } else
            echo "not matched";
    }
  //write json data into data.json file
    if (!file_put_contents($myFile, json_encode($arr_data, JSON_PRETTY_PRINT))) {
        echo "error";
    }
} catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "\n";
}

答案 1 :(得分:1)

您可以使用preg_replace。
Json的模式很容易预测。
使用正则表达式意味着您无需解码,编码甚至迭代数组。

$label = "yy";
$val = 20;

echo preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
                  "label\": \"" . $label . "\", \"val\": \"". $val, 
                  $json);

https://3v4l.org/m4rDa


如果您需要了解标签是否已更新,则可以使用以下方法:

$label = "yy";
$val = 20;

$new = Preg_replace("/label\":\s*\"" . $label . "\",\s*\"val\":\s*\"\d+/",
                  "label\": \"" . $label . "\", \"val\": \"". $val, 
                  $json);
If($json != $new){
    Echo "label updated\n";
}else{
    Echo "nothing found\n";
}
Echo $new;

它将比较“旧的” Json与新的Json,如果不匹配,则标签已更新。

答案 2 :(得分:1)

使用json_decode()和json_encode()的迭代解决方案

$jsonData = '[
    {
        "label": "aa",
        "val": "12"
    },
    {
        "label": "new",
        "val": "13"
    },
    {
        "label": "yy",
        "val": "14"
    }
]';

echo '<strong>Before update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';

$jsonArray = json_decode($jsonData, true);


foreach ($jsonArray as $key => $jsonRow) {
    if (isset($jsonRow['label']) && $jsonRow['label'] == 'yy') {
        $jsonArray[$key]['val'] = 20;
    }
}

$jsonData = json_encode($jsonArray, JSON_PRETTY_PRINT);

echo '<strong>After update</strong>';
echo '<pre>';
echo $jsonData;
echo '</pre>';

此代码将输出

更新前

[
    {
        "label": "aa",
        "val": "12"
    },
    {
        "label": "new",
        "val": "13"
    },
    {
        "label": "yy",
        "val": "14"
    }
]

更新后

[
    {
        "label": "aa",
        "val": "12"
    },
    {
        "label": "new",
        "val": "13"
    },
    {
        "label": "yy",
        "val": 20
    }
]