我已经有一段时间没有做过任何PHP编程了,所以我正试着摆脱生锈。
我正在尝试创建一个关联数组结构,如下所示。
[results]
[total]
[people]
[name]
[street]
[city]
[state]
[zip]
Currently, I have this.
$people = array( 'name' => '',
'street' => '',
'city' => '',
'state' => '',
'zip' => );
$results = array('total' => 10, --set dynamically
'people' => $people );
所以在我的脑海中,我希望创建一个空的多维数组,我可以在while循环中填充它。
首先,问题是这是正确的形式吗?我觉得我已经很接近了,但并不是正确的。这可能有助于理解我在做什么(如下所示)。
所以我说过,我想在while循环中填充它,这就是我到目前为止所得到的。到目前为止,我还不能去上班。
$i = 0;
while loop
{
$results['people'][i][name] = 'XxXxX'
$results['people'][i][street] = 'XxXxX'
$results['people'][i][city] = 'XxXxX'
$results['people'][i][state] = 'XxXxX'
$results['people'][i][zip] = 'XxXxX'
%i++;
}
我已经尝试了许多不同的组合,但仍然无法正确使用。如果重要的话,我想把这个数组作为JSON对象发送回浏览器。
我不确定是我的初始化错误,还是在循环中设置数组错误,或者两者兼而有之。
发布于 2012-12-01 04:10:04
PHP数组需要单独实例化,并就地实例化。我不知道如何恰当地描述它,但你的代码应该是这样的:
$results = array();
$results['total'] = $somevalue;
$results['people'] = array();
/*or:
$results = array(
'total' => $somevalue,
'people' => array()
);*/
$i = 0;
while($some_condition) { //or: for( $i=0; $i<$something; $i++ ) {
$results['people'][$i] = array();
$results['people'][$i]['name'] = 'XxXxX';
$results['people'][$i]['street'] = 'XxXxX';
$results['people'][$i]['city'] = 'XxXxX';
$results['people'][$i]['state'] = 'XxXxX';
$results['people'][$i]['zip'] = 'XxXxX';
/*or:
$results['people'][$i] = array(
'name' => 'XxXxX',
'street' => 'XxXxX',
'city' => 'XxXxX',
'state' => 'XxXxX',
'zip' => 'XxXxX',
);*/
$i++;
}
请记住,如果使用关联数组,则需要用引号将键字符串括起来。此外,您仍然可以使用整数索引访问关联数组,这是您应该感兴趣的。
发布于 2012-12-01 04:10:29
我看到了一些问题。稍后,您将引用i
而不是$i
。下一个是在while循环中,您试图在不使用引号的情况下访问名称、街道等(这可能会显示警告,也可能不会显示,这取决于您的配置)。
尝试使用以下命令:
$i = 0;
while(NEED SOME CONDITION HERE)
{
$results['people'][$i] = array(); //Need to let PHP know this will be an array
$results['people'][$i]['name'] = 'XxXxX'
$results['people'][$i]['street'] = 'XxXxX'
$results['people'][$i]['city'] = 'XxXxX'
$results['people'][$i]['state'] = 'XxXxX'
$results['people'][$i]['zip'] = 'XxXxX'
$i++;
}
发布于 2012-12-01 04:13:22
$i = 0;
while (true)
{
$results['people'][$i]['name'] = 'XxXxX'
$results['people'][$i]['street'] = 'XxXxX'
$results['people'][$i]['city'] = 'XxXxX'
$results['people'][$i]['state'] = 'XxXxX'
$results['people'][$i]['zip'] = 'XxXxX'
$i++;
}
https://stackoverflow.com/questions/13652323
复制相似问题