是否可以在PHP中的数组中定义变量字段名称?

时间:2013-01-09 09:41:49

标签: php arrays

我需要在数组中推送值,但是这个数组总是使用不同数量的元素,其中一些是编号的,我希望有类似的东西:

{"idWeb":223,"category":"animals","questionText":"have you got animals?","howManyAnswers":2,"answerText1":"yes","risid1":43,"answerText2":"no","risid2":44}

对于这个数组,例如变量名应该是answertext1和answertext2。

所以,我会有这样的事情:

$arrayname['answertext'.$a] = "some sentence string";

是不是?

2 个答案:

答案 0 :(得分:0)

是的,这是正确的.. 例如

$arr = array( 'a1'=>12,'a2'=>32,'a3'=>22,'a3'=>33 );
$x=1;
print_r($arr['a'.$x]);

这将输出12。

答案 1 :(得分:0)

是的,使用vars作为PHP中关联数组中的键名称没有问题,例如:

$a = 1;
$b = 2;

$arrayname['answertext'.$a] = "some sentence string A";
$arrayname['answertext'.$b] = "some sentence string B";

echo $arrayname['answertext'.$a] . "<br/>"; //"some sentence string A"
echo $arrayname['answertext1'] . "<br/>"; //"some sentence string A"

echo $arrayname['answertext'.$b] . "<br/>"; //"some sentence string B"
echo $arrayname['answertext2'] . "<br/>"; //"some sentence string B"

要使用array()创建关联数组,请使用=&gt;用于将索引与值分开的符号:

$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// a partir de PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

要构造一个空数组,不要将任何参数传递给array():

$addresses = array(  );

有关数组的更多信息: http://oreilly.com/catalog/progphp/chapter/ch05.html