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

在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']?

我很感激我能得到的任何帮助 - 我一直在寻找堆栈溢出而无法找到 任何与我想要完成的事情直接相关的事情。 p>

问题: strong>我正在尝试更新JSON文件中的特定名称/值对, 我试图通过AJAX调用发送特定参数到PHP文件来做到这一点。 其中两个参数是名称的路径(用连字符描绘),以及我正在交换的值。 p>

JSON的一小部分: p>

  {
“character”:
 {
“name”:“Foo”,
“species”:“Bar”,
} 
} 
  code>   pre> 
 
 

使用此JSON作为示例,我正在尝试更新特定的数组值,例如: p>

  $ char ['  character'] ['name'] 
  code>  pre> 
 
 

我正在使用路径信息将变量传递给PHP文件,例如: p> \ n

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

有没有办法转换字符串“character-name” (或具有特定描述的任何字符串)到数组中的路径,如 $ char ['character'] ['name'] code>? p> div>

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.

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)];
}

$array = explode("-", $_GET['char']);

$char=json_decode(....);  //your json string

$char[$array[0]][$array[1]]=$_GET['val'];

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?