数据未保存到阵列

时间:2017-04-25 02:03:39

标签: php arrays

为什么在下面的代码中我的所有数据都没有保存到数组中?

我可以在foreach中做一个var_dump,这会告诉我我想要的但是$cbContent只返回第一个对象?

代码:

$cbContent = array();

foreach ($guests as $guest)
{
  $cbContent[] = array(
   'FirstName' => $guest['FirstName'],
   'LastName' => $guest['LastName'],
   'Email' => $guest['email'],
   'Country' => $guest['country'],
   '_CheckIn' => $guest['check-in_date'],
   '_CheckOut' => $guest['check-out_date'],
  );
}
var_dump($cbContent); exit();

COD回复:

Array
(
    [FirstName] => Test
    [LastName] => Test
    [Email] => 
    [Country] => New Zealand
    [_CheckIn] => 2017-04-25
    [_CheckOut] => 2017-04-27
    [0] => Array
        (
            [FirstName] => Test 1
            [LastName] => Test 2
            [Email] => 
            [Country] => United Kingdom
            [_CheckIn] => 2017-04-25
            [_CheckOut] => 2017-04-26
        )

1 个答案:

答案 0 :(得分:0)

更新: 尝试使用:

array_push();

示例:

$cbContent = array();
foreach ($guests as $guest)
{
    $data = array(
       'FirstName' => $guest['FirstName'],
       'LastName' => $guest['LastName'],
       'Email' => $guest['email'],
       'Country' => $guest['country'],
       '_CheckIn' => $guest['check-in_date'],
       '_CheckOut' => $guest['check-out_date'],
      );
    if(empty($cbContent)){
        $cbContent = $data;
    } else {
        array_push($cbContent, $data);
    }
}