0

我有这个变量:

$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有了这些信息,get 和 ... 的更好方法是什么parent_id

4

6 回答 6

3
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';

"=>"不是 PHP 数组,您需要通过在其上展开并将其转换为数组,","并删除您发现的任何多余"的 's。

但是,您应该使用 JSON 并使用json_encodeandjson_decode

于 2013-09-30T20:30:15.137 回答
1

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";
    // ...
}

演示!

于 2013-09-30T20:59:13.973 回答
1

如果你想要动态的东西,你应该使用 JSON 编码并使用 json_decode 方法。JSON 是动态数据的良好标准。

http://php.net/manual/en/function.json-decode.php

于 2013-09-30T20:29:27.840 回答
1

我为你测试了这个:

<?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 () 被使用。有效。

于 2013-09-30T20:38:37.980 回答
0

一个快速而肮脏的解决方案可能是:

$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 );
于 2013-09-30T20:38:59.030 回答
0

这可能是您正在寻找的解决方案:

<?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 )
于 2013-09-30T20:52:01.273 回答