我有来自第三方插件的返回字符串,它看起来像是来自数组的var_dump。我正在尝试解析成一个有效的关联数组。查看各种示例并使用下面的代码进行一些测试。最后一部分展示了我遇到的问题。我正在尝试将数据解析为字符串,然后在我的数据字符串完成后以编程方式创建数组。当我在$ vegetables2上做print_r时,我得到:
数组([0] =>“Gourd”=“40 kilojoules”,“Artichoke”=“105 kilojoules”,“Cassava”=“550 kilojoules”)
echo $ vegetables2 [“Artichoke”]没有任何价值。有人可以用正确的语法指导我创建相当于前两个示例的数组吗?
//this works:
echo "From creating the entire array with a static string:<br/>";
$vegetables = array("Gourd"=>"40 kilojoules", "Artichoke"=>"105 kilojoules", "Cassava"=>"550 kilojoules");
echo "Artichoke: " . $vegetables["Artichoke"] . "<br/>";
//this works too
$vegetables1['Gourd'] = "40 kilojoules";
$vegetables1['Artichoke'] = "105 kilojoules";
$vegetables1['Cassava'] = "550 kilojoules";
echo "From creating one element at a time:<br/>";
echo "Artichoke: " . $vegetables1["Artichoke"] . "<br/>";
//this doesn't work
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
echo $strData ."<br/>";
$vegetables2 = array($strData);
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];
答案 0 :(得分:0)
$strData = "\"Gourd\"=\"40 kilojoules\",";
$strData = $strData . "\"Artichoke\"=\"105 kilojoules\",";
$strData = $strData . "\"Cassava\"=\"550 kilojoules\"";
$dd=str_replace('"','',"$strData");
$ff=explode(',',$dd);
foreach ($ff as $c)
{
$xx=explode('=',$c);
$vegetables2["$xx[0]"]=$xx[1];
}
print_r($vegetables2);
echo "Artichoke: " . $vegetables2["Artichoke"];