echo string / parameter into array - php

时间:2015-03-09 13:20:45

标签: php arrays insert

从文件中将键值插入php中的关联数组仍然存在问题。

<?
function RandomLine($filename) {
    $lines = file($filename);
    echo $lines[array_rand($lines)];
}

$a1 = RandomLine("p1.txt");

$a = array(
    1 => array(
        0 => "value1",
        1 => "value2",
        2 => "value3",
        3 => "value4",
        4 => "value5",
        7 => 4
    ),
    2 => array(
        0 => "value1a",
        1 => "value2a",
        2 => "value3a",
        3 => "value4a",
        4 => "value5a",
        7 => 4
    ),
    3 => array(
        //THE PROBLEM IS HERE, can't echo $a1 variable!
        echo $a1;
    ),
);

?>

文件p1.txt有两行:

0 => "value1",  1 => "value2",  2 => "value3",  3 => "value 4",  4 => "value5",  7 => 1
0 => "value6",  1 => "value7",  2 => "value8",  3 => "vealue9",  4 => "value10",  7 => 3

我收到错误:

Parse error: syntax error, unexpected T_ECHO, expecting ')'

有谁知道如何修复它?

2 个答案:

答案 0 :(得分:0)

您不会将值回显到数组中。

您只需使用其名称

3 => array(
    1 => $a1,

  ...
  ...
)

答案 1 :(得分:0)

删除最后一个数组后的逗号:

3 => array(
//THE PROBLEM IS HERE, can't echo $a1 variable!
echo $a1;
)

在数组deffinition之后移动echo:

3 => array(
  //THE PROBLEM IS HERE, can't echo $a1 variable!
  )
);
echo $a1;

如果你想从名为$ a的数组中回显一些东西,请执行以下操作:

echo $a[0];

这将只返回第一个数组,所以如果你想要&#34; value1&#34;从第一个数组做这样:

echo $a[1][0];