首页 > 解决方案 > 从数据库中获取数据并创建多维数组

问题描述

我想通过从数据库中获取数据来制作多维数组。但是,创建了由特定用户添加的播客的第二个数组,它没有给出在数据库中处于活动状态的另一个用户的输出。
这是我的代码:

require $_SERVER['DOCUMENT_ROOT'].'/config/init.php'; 

require CLASS_PATH.'user.php';
require CLASS_PATH.'podcast.php';
$user = new User();
$podcast = new Podcast();

$userList = $user->getAllUserName();

foreach ($userList as $users) {

    $fullname = $users->first_name. ' '. $users->last_name; 
    $data = array(
        'name'  => $fullname

    );

    $podcastList = $podcast->getUserPodcast($fullname);
    $data['podcast'] = $podcastList;
}

标签: phparraysjson

解决方案


您需要建立一个数据列表。将数据创建为 1 项将停止将podcast数据与fullname...

$userList = $user->getAllUserName();
$data = [];
foreach ($userList as $users) {
    $fullname = $users->first_name. ' '. $users->last_name; 
    $data[] = array(
        'name'  => $fullname,
        'podcast' => $podcast->getUserPodcast($fullname)
    );
}

仅限拥有播客的用户...

$userList = $user->getAllUserName();
$data = [];
foreach ($userList as $users) {
    $fullname = $users->first_name. ' '. $users->last_name; 
    $podcast = $podcast->getUserPodcast($fullname);
    if ( !empty($podcast) )  {
        $data[] = array(
            'name'  => $fullname,
            'podcast' => $podcast
        );
    }
}

推荐阅读