2012-10-11 49 views
2

在我的PHP代碼,我跑了一堆shell腳本終於輸出以下php數組不能正確增加。

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

上述輸出保存到$溫度。

然而,當我做回聲$臨時[0]它打印首開支架和回聲$臨時[1]打印單引號等.....

我相信這是因爲它是一個字符串而不是數組。

我想將其轉換爲n數組,每個元素與昏迷分隔。

但是,請注意,2003年10月20日有一個逗號,它應該保持它自己的元素。

有人可以指點我尋找什麼功能。

+0

數組位置「4」之前的字符串「u」是什麼? – Daedalus

+0

看看str_getcsv在php手冊http://nz1.php.net/str_getcsv – bumperbox

回答

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]) 
+0

答案更詳細.... +1 –

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'); 

然後$臨時[0]將返回正確的信息。

0

您的輸入看起來非常像一個js數組,除了神祕的u符號停留在單引號之外,其他所有答案似乎都忽略。我也是如此。如果您將單引號更改爲雙引號,則可以使用json_decode函數從js獲取數組。

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