我已经有一段时间没有做任何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循环。
首先,问题是这是正确的形式吗?我觉得我很接近,但不是对的。了解我在做什么可能会有帮助(如下所示)。
所以我说过,我想把这个填充到一个循环中,这就是我目前所拥有的。到目前为止,我还不能上班。
$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对象发送回浏览器。
我不确定我的初始化是错误的,在循环中设置数组是错误的,还是两者都是错误的。

最佳答案

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++;
}

请记住,如果使用关联数组,则需要用引号将键字符串括起来。此外,您仍然可以使用整数索引访问关联数组,您应该会有这种感觉。

10-08 08:35
查看更多