我有这个变量:
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
我想用数组方法从顶部变量中获取item_id和其他元素,所以我写了这个:
$value_arr = array($value);
$item_id = $value_arr["item_id"];
但是我收到错误Notice: Undefined index: item_id in file.php on line 115
但是当我使用此方法时,我成功地得到了很好的结果:
$value_arr = array("item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18);
$item_id = $value_arr["item_id"];
我该如何解决这个问题?
注意:我不想使用第二个方法,因为我的变量是动态的
更新:
文森特回答说我必须使用json_decode,我想问另一个问题以获得更好的方法,因为我拥有的原始字符串是:
[
{"item_id":null,"parent_id":"none","depth":0,"left":"1","right":18},
{"item_id":"1","parent_id":null,"depth":1,"left":2,"right":7},
{"item_id":"3","parent_id":null,"depth":1,"left":2,"right":7}
]
有了这些信息,有什么更好的方法来获得item_id
,parent_id
和...?
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
不是PHP数组,您需要通过在"=>"
和","
上将其爆炸来将其转换为数组,并删除您找到的任何额外"
。
但是,您应该使用 JSON 并使用 json_encode
和 json_decode
使用带有第二个参数的 json_decode()
作为TRUE
来获取关联数组作为结果:
$json = json_decode($str, TRUE);
for ($i=0; $i < count($json); $i++) {
$item_id[$i] = $json[$i]['item_id'];
$parent_id[$i] = $json[$i]['parent_id'];
// ...
}
如果要使用 foreach
循环执行此操作:
foreach ($json as $key => $value) {
echo $value['item_id']."'n";
echo $value['parent_id']."'n";
// ...
}
演示!
如果你想要一些动态的东西,你应该使用 JSON 编码并使用 json_decode 方法。JSON 是动态数据的良好标准。
http://php.net/manual/en/function.json-decode.php
我为您测试了一下:
<?php
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
eval("'$value_arr = array($value);");
print_r($value_arr);
?>
请检查。使用 PHP::eval()。成功了。
这可能是您正在寻找的解决方案:
<?php
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
$arr = explode(',',$value);
foreach($arr as $val)
{
$tmp = explode("=>",$val);
$array[$tmp[0]] = $tmp[1];
}
print_r($array);
?>
这将输出如下内容:
Array ( ["item_id"] => "null" ["parent_id"] => "none" ["depth"] => 0 ["left"] => "1" ["right"] => 18 )
一个快速而肮脏的解决方案可能是:
$array = json_decode( '{' . str_ireplace( '=>', ':', $value ) . '}', true );
// Array ( [item_id] => null [parent_id] => none [depth] => 0 [left] => 1 [right] => 18 )
编辑:关于问题的更新。
您的输入是一个json_encoded数组。只需json_decode它,您就完成了。
json_decode( $value, true );