0
請告訴我哪裏出錯了。我試圖將一個shell腳本的輸出分配給php中的一個數組。我做了很多搜索,但不知道我在尋找什麼。 !:(Shell腳本到多維數組php
// Run the command line script...
$myArray = shell_exec($cmd);
// "echo $myArray" returns something like this...
// array('example','example two',array('another level',array('level three')));
echo recursive_array($myArray);
// Returns this...
// Warning: Invalid argument supplied for foreach()
// Recursive array function
function recursive_array($array)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
recursive($value);
} else {
echo $key.' = '.$value, '<br/>';
}
}
}
// If I copy the output and manually define the
// array, the function seems to work as intended.
// $myArray = array('example','example two',array('another level', array('level three')));
感謝球員,這似乎這樣的伎倆這是我更新的代碼...
$result = shell_exec($cmd);
eval('$myArray = '.$result);
$html = recursive_array($myArray);
echo $html;
// Recursive Array Function
function recursive_array($array)
{
$content = '';
foreach($array as $key => $value)
{
if (is_array($value))
{
$content .= $key.'<br />'.recursive_array($value).'<br />';
} else {
$content .= $key.' = '.$value.'<br />';
}
}
return $content;
}
您可以使用eval()將shell命令輸出作爲字符串傳遞並創建數組,但eval()是EVIL :) –