在PHP中推送多维数组中的元素

时间:2018-05-28 20:27:28

标签: php arrays

所以我正在处理一个多维数组。

例如,我想要获得的输出数据是这样的:

[[element 1],[element 2], [element 3]]

这是我的PHP代码(减去整个准备好的语句,它超出了绑定((不包括在内,因为这工作正常)):

$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_fcm_old, $vessel_hull_id_new, $vessel_hull_id_old, $vessel_name_new, $vessel_name_old, $vessel_length_new, $vessel_length_old, $vessel_manufacturer_new, $vessel_manufacturer_old, $vessel_manufacturer_id_new, $vessel_manufacturer_id_old, $vessel_year_new, $vessel_year_old, $vessel_value_new, $vessel_value_old, $owner_id_new, $owner_id_old, $loss_payee_id_new, $loss_payee_id_old, $policy_id_new, $policy_id_old, $policy_start_date_new, $policy_start_date_old, $policy_end_date_new, $policy_end_date_old, $vessel_fcm, $vessel_hull_id, $vessel_name, $vessel_manufacturer_id);
while ($insertquery->fetch()){
    if($vessel_fcm_new != $vessel_fcm_old){
        $data = array($vessel_fcm_new, $vessel_fcm_old);
    }
    if ($vessel_name_new != $vessel_name_old){
         array_push($data, $vessel_name_new, $vessel_name_old);
    }
    $data_return[] = $data;
}
echo json_encode($data_return);

基本上,代码被启动以遍历每个数据库行,如果满足条件,它将构建一个数组,并将该数组添加到数组对象中。如果满足匹配条件,结果将如此:

[[row 1], [row2], [row3]]

但是,我收到此错误:

Warning: array_push() expects parameter 1 to be array, null given in C:\htdocs\alterajax.php on line 16

但是我已经指定了数组,或者至少我认为我是($data)。 这也是我看到的输出:

[null,null,null,null,null,["FCMjgis","fFH465","Smokey","GIIGE"]]

我确定这只是一些小问题,但如果你能提供帮助我会很感激。提前谢谢!

2 个答案:

答案 0 :(得分:1)

就像我说的那样,只需初始化变量或测试是否使用isset

进行初始化
$insertquery->bind_result($tracking_type, $tracking_change_date, $vessel_fcm_new, $vessel_fcm_old, $vessel_hull_id_new, $vessel_hull_id_old, $vessel_name_new, $vessel_name_old, $vessel_length_new, $vessel_length_old, $vessel_manufacturer_new, $vessel_manufacturer_old, $vessel_manufacturer_id_new, $vessel_manufacturer_id_old, $vessel_year_new, $vessel_year_old, $vessel_value_new, $vessel_value_old, $owner_id_new, $owner_id_old, $loss_payee_id_new, $loss_payee_id_old, $policy_id_new, $policy_id_old, $policy_start_date_new, $policy_start_date_old, $policy_end_date_new, $policy_end_date_old, $vessel_fcm, $vessel_hull_id, $vessel_name, $vessel_manufacturer_id);
while ($insertquery->fetch()){
    if($vessel_fcm_new != $vessel_fcm_old){
        $data = array($vessel_fcm_new, $vessel_fcm_old);
    }
    if (isset($data) && $vessel_name_new != $vessel_name_old){
         array_push($data, $vessel_name_new, $vessel_name_old);
         $data_return[] = $data;
    }
}
echo json_encode($data_return);

答案 1 :(得分:0)

确保初始化变量!

在这种情况下,我需要做的就是初始化$ data数组。我通过将$data = [];(或$data = array();)放在while循环上方的行上来完成此操作