Результаты PHP Group / Nest Array - PullRequest
0 голосов
/ 25 февраля 2019

У меня есть ряд студентов, которые зачислены для обучения, которые мне нужно отобразить, сгруппированные по дате их обучения, а затем по организации.

Но меня это совсем озадачило.Массив выглядит примерно так:

$bookings = 
array(
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 1" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 2" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 3" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 4" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 5" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 6" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 7" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 8" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 9" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 10" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 11" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 12" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 13" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 14" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 15" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 16" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 17" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 18" )
);

В этом примере есть 3 даты, 5 компаний и 18 студентов. Я пытаюсь их вложить, создавая даты и резервируя массивы из основного массива заранее для созданияследующий результат:

<div class="Date">Bookings for 12/05/2019</div>
    <div class="Company">Booked for Company 1</div>
        <div class="Student">Student 1</div>
        <div class="Student">Student 2</div>
        <div class="Student">Student 3</div>
        <div class="Student">Student 4</div>
        <div class="Student">Student 5</div>
    <div class="Company">Booked for Company 2</div>
        <div class="Student">Student 6</div>
        <div class="Student">Student 7</div>
        <div class="Student">Student 8</div>
<div class="Date">Bookings for 19/05/2019</div>
    <div class="Company">Booked for Company 3</div>
        <div class="Student">Student 9</div>
        <div class="Student">Student 10</div>
        <div class="Student">Student 11</div>
        <div class="Student">Student 12</div>
<div class="Date">Bookings for 26/05/2019</div>
    <div class="Company">Booked for Company 4</div>
        <div class="Student">Student 13</div>
        <div class="Student">Student 14</div>
        <div class="Student">Student 15</div>
    <div class="Company">Booked for Company 5</div>
        <div class="Student">Student 16</div>
        <div class="Student">Student 17</div>
        <div class="Student">Student 18</div>

Но, конечно, мое элементарное знание PHP подвело меня, и я просто не понимаю его.Я просто потерян.

Мой ужасный код в настоящее время выглядит так:

$by_date = array();

foreach( $bookings as $dte )
    {
        $by_date['Date'][] = $dte['Date'];
    }

$by_company = array();

foreach( $bookings as $comp )
    {
        $by_company['Company'][] = $comp['Company'];
    }


foreach($by_date as $did => $company_array)
{
    $b_date = $company_array[0]['Date'];
    echo '<div class="Date">Bookings for '.$b_date.'</div>';
        foreach( $by_company as $cid => $student_array )
        {
            $c_name = $student_array[0]['Company'];
            echo '<div class="Company">Bookings for '.$c_name.'</div>';

            foreach( $student_array as $student )
            {
                $stud = $student[0]['Student'];
                echo '<div class="Student">'.$stud.'</div>';
            }
        }
}

Любая помощь будет принята с благодарностью.

Ответы [ 3 ]

0 голосов
/ 25 февраля 2019

Заставьте $bookings стать многомерным массивом

$bookings =
    array(
        array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 1" ),
        array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 2" ),
        array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 3" ),
        array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 4" ),
        array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 5" ),
        array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 6" ),
        array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 7" ),
        array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 8" ),
        array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 9" ),
        array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 10" ),
        array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 11" ),
        array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 12" ),
        array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 13" ),
        array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 14" ),
        array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 15" ),
        array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 16" ),
        array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 17" ),
        array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 18" )
    );
$arr = [];
foreach ($bookings as $row){
    $arr[$row['Date']][$row['Company']][] = $row['Student'];
}

Будет возвращен новый массив:

Array
(
[12/05/2019] => Array
    (
        [Company 1] => Array
            (
                [0] => Student 1
                [1] => Student 2
                [2] => Student 3
                [3] => Student 4
                [4] => Student 5
            )
     )
)

Затем вы можете продолжить работу массива, используя 3 цикла, как показано ниже.

foreach ($arr as $date => $companies){
    echo  ' <div class="Date">Bookings for '.$date.'</div>';
    foreach ($companies as $company=> $students){
        echo '<div class="Company">Bookings for '.$company.'</div>';
        foreach ($students as $student){
            echo '<div class="Student">'.$student.'</div>';
        }
    }
}
0 голосов
/ 25 февраля 2019

Еще один забавный способ сделать это с помощью функций ....

<?php

    $array = 
array(
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 1" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 2" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 3" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 4" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 5" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 6" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 7" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 8" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 9" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 10" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 11" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 12" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 13" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 14" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 15" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 16" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 17" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 18" )
);


function formatnewarray ( $array, $group_by, $order_by )
{
    $return = array ( );

    $holder = '';

    foreach ( $array AS $value )
    {
        if ( is_array ( $group_by ) )
        {
            $temp = '';

            foreach ( $group_by AS $group )
            {
                $temp .= '[' . $value[$group] . ']';
            }

            $holder .= 'out' . $temp . '[]=' . $value[$order_by] . '&';
        }
        else
        {
            $holder .= 'out[' . $value[$group_by] . '][]=' . $value[$order_by] . '&';
        }
    }

    parse_str ( $holder );

    return $out;
}

function array2html ( $data )
{
    $out = '';

    foreach ( $data AS $date => $companys )
    {
        $out .= "<div class='Date'>Bookings for " . $date . "</div>\r\n";       

        foreach ( $companys AS $company => $students )
        {
            $out .= "<div class='Company'>Booked for " . $company . "</div>\r\n";

            foreach ( $students AS $student )
            {
                $out .= "<div class='Student'>" . $student . "</div>\r\n";
            }
        }
    }

    return $out;
}

$group_by = array ( 'Date', 'Company' );

$order_by = 'Student';

/* reformat array */

$data = formatnewarray ( $array, $group_by, $order_by );

/* new formatted array */

print_r ( $data );

/* build the html from the new formatted array */

$data = array2html ( $data );


/* echo the formatted html */

echo $data;


?>
0 голосов
/ 25 февраля 2019

Этот трюк: изменить текущий массив на массив деревьев.Ключ - Данные, и Компания:

Совет: в PHP 7 вы можете объявить массив с помощью []

$bookings = 
array(
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 1" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 2" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 3" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 4" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 1","Student"=>"Student 5" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 6" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 7" ),
    array( "Date"=>"12/05/2019","Company"=>"Company 2","Student"=>"Student 8" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 9" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 10" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 11" ),
    array( "Date"=>"19/05/2019","Company"=>"Company 3","Student"=>"Student 12" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 13" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 14" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 4","Student"=>"Student 15" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 16" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 17" ),
    array( "Date"=>"26/05/2019","Company"=>"Company 5","Student"=>"Student 18" )
);

$result = [];
foreach($bookings as $itemBooking){
    $result[$itemBooking["Date"]][$itemBooking["Company"]][]=$itemBooking["Student"];
}

foreach($result as $date => $company_array)
{
    echo '<div class="Date">Bookings for '.$date.'</div>';
        foreach( $company_array as $company => $student_array )
        {
            echo '<div class="Company">Bookings for '.$company.'</div>';

            foreach( $student_array as $student )
            {
                echo '<div class="Student">'.$student.'</div>';
            }
        }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...