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 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号