Реструктурировать массив из SQL-запроса, чтобы я мог отображать правильные значения

0

Я пытаюсь получить содержимое, которое мне нужно из объединенного запроса, и правильно использовать значения в качестве ключа массива, чтобы я мог правильно создавать некоторые списки DIV

Мой php-запрос и массив:

$getTickers = "
    SELECT d.ID as displayID, d.display_name as display, l.location_name as locationName, d.location_id as location, t.id as ticker, tc.id as contentID, tc.content
        FROM displays d
            INNER JOIN locations l on d.location_id = l.id
            INNER JOIN tickers t on d.id = t.display_id
            INNER JOIN ticker_content tc on t.id = tc.ticker_id;
";

$tickers = $mysqlConn->query($getTickers);

$tickerDisplays = array();
foreach($tickers as $subArray) {
    if(!array_key_exists($subArray['displayID'], $tickerDisplays)) {
        $tickerDisplays[$subArray['displayID']] = array();

    }
    // here you add 'display_name' under key 'display_id'
    $tickerDisplays[$subArray['displayID']][$subArray['location']] = $subArray['display'];
}

Все примеры и код ниже, но мне не нужна помощь в структуре html, просто как реструктурировать массив/ключ, чтобы дать мне желаемые результаты и как я должен зацикливать их на переднем конце.

Я получаю 4 divs, как я ожидаю, прямо сейчас (по одному для каждого уникального отображения/местоположения), но мне нужно выяснить, как правильно организовать его, чтобы я мог повторить имя DIsplay как h4, местоположение как h5, а затем каждый содержание в моем списке

Поэтому результат запроса дает мне следующее:

displayID | display |  locationName  | location | ticker | contentID |    content         | 

  1         Office      Building 4       4         1          1         testing content
  2         Lobby       Building 4       4         2          2         testing content 2
  3         Lobby       Building 1       1         3          3         testing content 3
  4         Office      Building 1       1         4          4         testing content 4
  4         Office      Building 1       1         4          5         testing content again

Я пытаюсь выполнить цикл с ожидаемым результатом наличия aa div для каждой комбинации местоположения/отображения следующим образом:

OFFICE           
Building 4

testing content

---------------

LOBBY           
Building 4

testing content 2

------------------

LOBBY           
Building 1

testing content 3

------------------


OFFICE 
Building 1

testing content 4
testing content again

----------------------

Вот как я сейчас пытаюсь

<?php foreach($tickerDisplays as $key => $ticker):?>

        <h4><?php echo $key ?></h4>     //so this should be the display Name (office, lobby)
        <h5><?php echo //location?></h5> //this should be the location name (Building 1, Building 4)

        //This will be another foreach for any content associated with the location/display
        <ul class="tickerContent">
            <li>
        </ul>
      </div>
    </div>
<?php endforeach;?>
  • 0
    Я предполагаю, что displayID будет отображаться в результате запроса несколько раз из-за объединений?
  • 0
    Да, это правильно, так как несколько записей контента будут назначены на один дисплей
Показать ещё 5 комментариев
Теги:
arrays
loops

1 ответ

1
Лучший ответ

Подход здесь состоит в том, чтобы создать дочерний массив для каждой строки отображения, содержащий все записи нескольких материалов.

// Dummy the data from the query
$tickers = [

['displayID' => 1,          'display' => 'Office',      'locationName' => 'Building 4',        'location' => 4,          'ticker' => 1,          'contentID' => 1,          'content' => 'testing content'],
['displayID' => 2,          'display' => 'Lobby',       'locationName' => 'Building 4',        'location' => 4,          'ticker' => 2,          'contentID' => 2,          'content' => 'testing content 2'],
['displayID' => 3,          'display' => 'Lobby',       'locationName' => 'Building 1',        'location' => 1,          'ticker' => 3,          'contentID' => 3,          'content' => 'testing content 3'],
['displayID' => 4,          'display' => 'Office',      'locationName' => 'Building 1',        'location' => 1,          'ticker' => 4,          'contentID' => 4,          'content' => 'testing content 4'],
['displayID' => 4,          'display' => 'Office',      'locationName' => 'Building 1',        'location' => 1,          'ticker' => 4,          'contentID' => 5,          'content' => 'testing content again']
];

// A place to keep the reorganized data
$tickerDisplays = [];

// Walk through the query result
foreach($tickers as $row) {
    $displayID = $row['displayID']; // for convenience and readability
    $location = $row['location'];   // for convenience and readability
    $display = $row['display'];
    $contentID = $row['contentID'];

    if ( ! array_key_exists($row['displayID'], $tickerDisplays) ) {
        $tickerDisplays[$displayID] = [
            'displayID' => $row['displayID'],
            'display' => $row['display'],
            'ticker' => $row['ticker'],
            'contentID' => $row['contentID'],
            'content' => $row['content'],
            'location' => $row['location'],
            'locationName' => $row['locationName'],
            '@content' => [] // to store the content data                
        ];

    }
    $tickerDisplays[$displayID]['@content'][$contentID] = ['content' => $row['content']];
}

print_r($tickerDisplays);

foreach ( $tickerDisplays as $key => $ticker ) {
    // Output the display and location name
    out($ticker['display']);
    out($ticker['locationName']);
    // Output all the content records.
    foreach ( $ticker['@content'] as $contentID => $content ) {
        out($content['content']);
    }
    out('------------');
}
// Just a utility function
function out($msg) {
    echo "$msg\n";
}

Выход:

Office
Building 4
testing content
------------
Lobby
Building 4
testing content 2
------------
Lobby
Building 1
testing content 3
------------
Office
Building 1
testing content 4
testing content again
------------
  • 0
    Я думаю, что все закончилось тем, что я хотел, спасибо!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню