dps69208 2014-04-17 14:28
浏览 61
已采纳

在PHP中将描述的字符串转换为数组路径

I'd appreciate any help I could get with this — I've been scouring stack overflow and couldn't find anything that directly related with what I'm trying to accomplish.

Issue: I'm trying to update a specific name/value pair in a JSON file, and I'm trying to do it by sending specific parameters through an AJAX call to a PHP file. Two of the parameters are the path (delineated with hyphens) to the name, and the value that I'm swapping in.

A small portion of the JSON:

{
  "character" : 
  {             
    "name" : "Foo",
    "species" : "Bar",
  }
}

Using this JSON as an example, I'm trying to update a specific array value, such as:

$char['character']['name']

I'm passing a variable to the PHP file with the path information, such as:

updater.php?char=character-name&val=Newname  

Is there a way to convert the string "character-name" (or any string for that matter with a particular delineation) to the path in an Array, like $char['character']['name']?

  • 写回答

4条回答 默认 最新

  • dongwh1992 2014-04-17 15:00
    关注

    To not only read the value at the specified path, but also update the json, I would suggest something like

    <?php
    function json_replace_path($json, $path, $newValue)
    {
        $json = json_decode($json);
    
        $pathArray = explode('-', $path);
        $currentElement = $json;
    
        foreach ($pathArray as $part)
        {
            $currentElement = &$currentElement->$part;
        }
    
        $currentElement = $newValue;
    
        return json_encode($json);
    }
    
    $json = '{"character":{"name":"Foo","species":"Bar","other":{"first_name":"Jeff","last_name":"Atwood"}}}';
    echo json_replace_path($json, 'character-name', 'new name') . "
    ";
    echo json_replace_path($json, 'character-species', 'new species') . "
    ";
    echo json_replace_path($json, 'character-other-last_name', 'Bridges') . "
    ";
    

    Does not support JSON including arrays, though.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 cplex运行后参数报错是为什么
  • ¥15 之前不小心删了pycharm的文件,后面重新安装之后软件打不开了
  • ¥15 vue3获取动态宽度,刷新后动态宽度值为0
  • ¥15 升腾威讯云桌面V2.0.0摄像头问题
  • ¥15 关于Python的会计设计
  • ¥15 聚类分析 设计k-均值算法分类器,对一组二维模式向量进行分类。
  • ¥15 stm32c8t6工程,使用hal库
  • ¥15 找能接spark如图片的,可议价
  • ¥15 关于#单片机#的问题,请各位专家解答!
  • ¥15 博通raid 的写入速度很高也很低