如何获得关联数组的多个实例?

时间:2019-04-07 18:28:20

标签: php

我正在执行GET请求。我需要“组”具有相同关联数组的多个实例(“时间” =>字符串,“会话” => array())。我的前端使用此特定的.json结构。

我在while循环中使用了array_push。我还尝试构建一个临时数组,然后推送它,但是我推送的最后一个数组会覆盖最后一个。

<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// include database and object files
include_once '../config/database.php';
include_once '../objetos/token.php';
include_once '../objetos/log.php';
include_once '../objetos/agenda.php';
$idLogAccion = 16;

//Leo los parametros


// instantiate database and product object
$database = new Database();
$db = $database->getConnection();


// initialize object
$miAgenda = new agenda($db);


$respuesta_arr=array();
$respuesta_arr["schedule"]=array();
$respuesta_arr["speakers"]=array();

$groups_arr["groups"]=array();
$respuesta_arr["schedule"]["date"]="2018-05-17";
$respuesta_arr["schedule"]["groups"]=array('time'=>'','sessions'=>array());



$listaEventos = $miAgenda->obtenerEventos();
$numeroEventos = $listaEventos->rowCount();

$listSpeakers = $miAgenda->obtenerOradores();
$numeroSpeakers = $listSpeakers->rowCount();

if($numeroSpeakers>0){

    // retrieve our table contents
    while ($row = $listSpeakers->fetch(PDO::FETCH_ASSOC)){

        // extract row
        extract($row);

        $speakers_item=array(
            "idEvento" => $idEvento,
            "nombre" => $nombre." ".$apellido,
            "fotoPerfil" => $fotoPerfil,
            "mail" => $mail
        );

        array_push($respuesta_arr["speakers"],$speakers_item);


    }

    //$stmt = $milog->logear($idUsuario, $idLogAccion,$versionApp);

}
$listSpeakers = $miAgenda->obtenerOradores();

$rowSpeakers = $listSpeakers->fetchAll(PDO::FETCH_ASSOC);

if($numeroEventos>0){

    //$respuesta_arr["schedule"]["date"]='asd';

    // retrieve our table contents
    while ($rowEvento = $listaEventos->fetch(PDO::FETCH_ASSOC)){

        // extract row
        extract($rowEvento);
        $eventos_item=array(
            "id" => $idEvento,
            "idCongreso" => $idCongreso,
            "timeStart" => $horarioComienzo,
            "description"=> "Mobile devices, etc.",
            "timeEnd" => $horarioFin,
            "location" => $sala,
            "name" => $nombreEvento,
            "idDia" => $idDia,
            //"hora" => $hora,   // NO NECESITO LA HORA ACA
            "speakerNames" => array()
        );


        // agregamos los speakers
        if($numeroSpeakers>0){

            // retrieve our table contents
            $speakerTmp=array();
                foreach($rowSpeakers as $row) { //por cada registro en rowSpeakers


                    if ($row['idEvento'] == $rowEvento['idEvento']){ //Si el speaker tiene idEvento igual a idEvento de este evento

                        $speakerTmp=$row['nombre']." ".$row['apellido'];  


                    array_push($eventos_item["speakerNames"],$speakerTmp);  //Lo agrego al array de speakers
                    }

                }
                if($horaPrev!=$hora){
                    $respuesta_arr["schedule"]["groups"]["time"]=$hora;

                        // print_r("Same Time");

                    }
                if($horaPrev!=$hora && $horaPrev!=null){
                    $respuesta_arr["schedule"]["groups"]["time"]=$hora;

                    // print_r("New Time"); 

                }

                $horaPrev=$hora;



            }
            array_push($respuesta_arr["schedule"]["groups"]["sessions"],$eventos_item);

            //array_push($groups_arr["groups"],$eventos_item);  // TODO: cargar uno por uno, no el array entero
        }



        //TODO: Divido por horas




}





http_response_code(200);
echo json_encode($respuesta_arr);


?>

预期结果

{
    "schedule": {
        "date": "2018-05-17",
    "groups": [{
      "time": "8:00 am",
      "sessions": [{
            "id": "1",
            "idCongreso": "1",
            "timeStart": "08:00:00",
            "description": "Mobile devices, etc.",
            "timeEnd": "09:00:00",
            "location": "condor",
            "name": "Maternidad deseada",
            "idDia": "1",
            "speakerNames": [
                "apellido1 usuario1",
                "apellido2 usaurio2"
            ]
        }]
    },{

        "time":"22:00 PM",
        "sessions": [{
            "id": "2",
            "idCongreso": "1",
            "timeStart": "22:30:00",
            "description": "Mobile devices, etc.",
            "timeEnd": "13:00:00",
            "location": "condorito",
            "name": "Legal y clandestino",
            "idDia": "2",
            "speakerNames": [
                "apellido1 usuario1",
                "apellido3 Usuario3"
            ]
        }]

    }
    ],
    "speakers": [
        {
            "idEvento": "1",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "1",
            "nombre": "apellido2 usaurio2",
            "fotoPerfil": null,
            "mail": "1235"
        },
        {
            "idEvento": "2",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "2",
            "nombre": "apellido3 Usuario3",
            "fotoPerfil": null,
            "mail": "1236"
        }
    ]
  }
}

实际结果

{
    "schedule": {
        "date": "2018-05-17",
        "groups": {
            "time": "22:00 PM",
            "sessions": [
                {
                    "id": "1",
                    "idCongreso": "1",
                    "timeStart": "08:00:00",
                    "description": "Mobile devices, etc.",
                    "timeEnd": "09:00:00",
                    "location": "condor",
                    "name": "Maternidad deseada",
                    "idDia": "1",
                    "speakerNames": [
                        "apellido1 usuario1",
                        "apellido2 usaurio2"
                    ]
                },
                {
                    "id": "2",
                    "idCongreso": "1",
                    "timeStart": "22:30:00",
                    "description": "Mobile devices, etc.",
                    "timeEnd": "13:00:00",
                    "location": "condorito",
                    "name": "Legal y clandestino",
                    "idDia": "2",
                    "speakerNames": [
                        "apellido1 usuario1",
                        "apellido3 Usuario3"
                    ]
                }
            ]
        }
    },
    "speakers": [
        {
            "idEvento": "1",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "1",
            "nombre": "apellido2 usaurio2",
            "fotoPerfil": null,
            "mail": "1235"
        },
        {
            "idEvento": "2",
            "nombre": "apellido1 usuario1",
            "fotoPerfil": "jorgeBasualdo.png",
            "mail": "1234"
        },
        {
            "idEvento": "2",
            "nombre": "apellido3 Usuario3",
            "fotoPerfil": null,
            "mail": "1236"
        }
    ]
}

1 个答案:

答案 0 :(得分:0)

你有一个数组

$respuesta_arr=array();

现在您添加组时间表和发言人:

$respuesta_arr["schedule"]=array();
$respuesta_arr["speakers"]=array();

现在您添加嵌套数据:

$respuesta_arr["schedule"]["date"]="2018-05-17";
$respuesta_arr["schedule"["groups"]=array();

现在添加组数据

$respuesta_arr["schedule"]["groups"][] = array('time'=>'','sessions'=>array())

如果愿意,您可以立即执行以下操作:

 $respuesta_arr = array(
    "schedule" => array(
      "date" => "2018-05-17",
      "groups" => array(
         array('time'=>'','sessions'=>array()),
         array('time'=>'','sessions'=>array())
       )
     ),
    "speakers" => array()
 );

您有两个错误:$groups_arr,并且必须使用array(array(...))[]嵌套数组。您还可以查看以下文档:https://www.php.net/manual/en/language.types.array.php