dps69208
2014-04-17 14:28 阅读 41

在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 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.

    点赞 评论 复制链接分享
  • dongsunny1113 dongsunny1113 2014-04-17 14:32

    Something like that should work, I guess :

    $a = explode("-", $_GET['char']);
    $array = ...; //Your json array here
    
    while (is_array($array) && count($a) > 0)
    {
        $array = $array[array_shift($a)];
    }
    
    点赞 评论 复制链接分享
  • doumengbai2031 doumengbai2031 2014-04-17 14:35
    $array = explode("-", $_GET['char']);
    
    $char=json_decode(....);  //your json string
    
    $char[$array[0]][$array[1]]=$_GET['val'];
    
    点赞 评论 复制链接分享
  • duanhai4046 duanhai4046 2014-04-17 14:49

    Why not just use updater.php?character[name]=Newname? Then you can get it with:

    echo $_GET['character']['name'];
    

    Makes much more sense. Why concatenate things and then try and separate them into an array when you can just use an array from the start?

    点赞 评论 复制链接分享

相关推荐