php数组没有正确增加。

时间:2012-10-11 09:01:19

标签: php

在我的PHP代码中,我运行了一堆shell脚本,最终输出以下内容

['October 20, 2003', '047085815X', '978-\n0470858158', '1', u'\nWireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n']

以上输出保存到$ temp。

然而,当我回显$ temp [0]时,它会打印出第一个开放式括号并且echo $ temp [1]打印单引号等......

我相信这是因为它是一个字符串而不是一个数组。

我想将此转换为n数组,每个元素都用昏迷分隔。

然而,请注意,2003年10月20日有一个逗号,它应该保留自己的元素。

有人能指出我正在寻找的功能吗?

4 个答案:

答案 0 :(得分:2)

修剪开始和结束[],然后使用str_getcsv()

答案 1 :(得分:1)

我认为这是你正在寻找的功能

str_getcsv()

快速示例

$line = "'October 20, 2003', '047085815X', '978-\n0470858158', '1', '\nWireless     Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n'";

$parsed = str_getcsv(
  $line, # Input line
  ",",   # Delimiter
  "'"   # Enclosure
);

print_r($parsed);

输出:

Array ( [0] => October 20, 2003 [1] => 047085815X [2] => 978- 0470858158 [3] => 1 [4] => Wireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover] ) 

答案 2 :(得分:0)

你所拥有的似乎更接近javascript数组。我不知道你的shell脚本是如何工作的,但我知道如何形成php数组;你需要以下内容来形成一个php数组:

$temp = array('item1','item2','etc');

所以对你来说,我输出以下内容,减去方括号:

$temp = array('October 20, 2003', '047085815X', '978-\n0470858158', '1', '\nWireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n');

然后$ temp [0]将返回正确的信息。

答案 3 :(得分:0)

您的输入看起来非常像js数组,除了单引号之外的神秘u符号,其他答案似乎都忽略了。我也是如此。如果你将单引号改为双引号,你将能够使用json_decode函数从js中获得 php 数组。

$str = '["October 20, 2003", "047085815X", "978-\n0470858158", "1", "\nWireless Foresight: Scenarios of the Mobile World in 2015 [Hardcover]\n"]';
print_r(json_decode($str));