php字符串变量包含作为数组函数的输入
为什么这不起作用?
$stringhaha =" 1 => General,
2 => Business,
3 => Entertainment,
4 => Health,
5 => Politics,
6 => Sci/Tech,
7 => Sports,
8 => News";
$all_categories = array($stringhaha);
print_r($all_categories);
(将给出一个包含 1 项的数组。)
虽然这有效: 如果我包含这样的变量内容,它将正确创建一个包含 8 个项目的数组:
$all_categories = array(1 => General,
2 => Business,
3 => Entertainment,
4 => Health,
5 => Politics,
6 => Sci/Tech,
7 => Sports,
8 => News);
print_r($all_categories);
Why this does not work?
$stringhaha =" 1 => General,
2 => Business,
3 => Entertainment,
4 => Health,
5 => Politics,
6 => Sci/Tech,
7 => Sports,
8 => News";
$all_categories = array($stringhaha);
print_r($all_categories);
(will give an array with 1 item.)
While this works:
If I include the variable content like this it will create properly an array with 8 items:
$all_categories = array(1 => General,
2 => Business,
3 => Entertainment,
4 => Health,
5 => Politics,
6 => Sci/Tech,
7 => Sports,
8 => News);
print_r($all_categories);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正在发生的事情正是您所期望的:您已经声明了一个包含一个字符串的数组。
对于我们人类来说,你的字符串看起来像一个数组并不重要,PHP 仅仅是 PHP,并且无法神奇地检测到你希望它从字符串解析数组。
giorgio79,来认识一下 PHP Docs,你的新好朋友。
What is happening is exactly what you should expect: you've declared an array that contains one string.
It doesn't matter that your string looks like an array to us humans, PHP is merely PHP, and can't magically detect that you want it to parse an array from a string.
giorgio79, meet PHP Docs, your new best friend.
这就是所谓的语言语法。你不能为所欲为。你必须说出它的设计方式。
这也不起作用
为什么?因为它在语法上不正确。这同样适用于您的数组示例。
这是正确的
每种语言都有规则,你必须尊重它们。祝你好运。
It's called language syntax. You cannot do whatever you want. You have to speak the language how it was designed.
This doesn't work either
Why? Because it's not syntactically correct. Same applies for your example with array.
This is correct
Every language has rules and you have to respect them. Good luck.
我认为正确的语法是:
您确实想要一个字符串数组,对吧?
I think the correct syntax is:
You do want an array of strings, right?