0

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

{"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";

这样对吗?

4

2 回答 2

0

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

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

这将输出 12。

于 2013-01-09T09:53:10.660 回答
0

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

$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( ) 创建关联数组,请使用 => 符号将索引与值分开:

$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

于 2013-01-09T10:00:29.943 回答