php关联数组爆炸问题
我有如下的 php 脚本;
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$array = explode(",", $ages2);
echo $array["Peter"];
echo $ages["Peter"];
在这种情况下,echo $ages["Peter"];
工作正常,但 echo $array["Peter"];
不起作用。任何人都可以解决这个问题吗?
提前致谢。
巴塞拉弗雷德
I have php script as below;
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages2 = '"Peter"=>32, "Quagmire"=>30, "Joe"=>34';
$array = explode(",", $ages2);
echo $array["Peter"];
echo $ages["Peter"];
In this case, echo $ages["Peter"];
is working well, but echo $array["Peter"];
is not working. Can anybody solve this please..
Thanks in advance.
blasteralfred
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须分两步进行:
', '
作为分隔符进行爆炸;获取诸如"Peter"=>32
之类的数据'=>'
作为分隔符进行爆炸,以拆分姓名和年龄例如,您可以使用如下内容:
并且,转储数组,您将得到以下输出:
这意味着使用这个:
会得到:
You'll have to go in two steps :
', '
, as a separator ; to get pieces of data such as"Peter"=>32
'=>'
as a separator, to split the name and the ageFor example, you could use something like this :
And, dumping the array, you'd get the following output :
Which means that using this :
Would get you :
当然是行不通的。 explode 只是按给定的分隔符进行分割,但不会创建关联数组。
Of course it doesn't work. explode just splits by the given delimiter but doesn't create an associative array.
如果您确实有这样的字符串,您唯一的希望就是手动解析它。要么使用 preg_match_all,要么我想你可以这样做:
但当然不建议这样做,因为它可能会在很多方面出错。
无论如何,我非常确定您可以重构此代码,或者如果您需要更多帮助,可以为我们提供更多背景信息。
Your only hope if you really have such a string is to parse it manually. Either using preg_match_all, or I suppose you could do:
But of course this isn't recommended since it could go wrong in many many ways.
In any case I'm pretty sure you can refactor this code or give us more context if you need more help.
您需要通过提取姓名和年龄来自己构建数组:
You'll need to build the array yourself by extracting the name and age:
$ages2 不是一个数组,所以你在这里尝试的不会直接起作用,但是你可以将具有该结构的字符串转换为这样的数组:
如果你 var_dump($array),你将拥有:
所以你可以按预期执行此操作并返回 32:
$ages2 is not an array, so what you're trying here won't work directly, but you can transform a string with that structure into an array like this:
If you var_dump($array), you'll have:
So you can do this as expected and get 32 back out: