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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里