将多个不同的动态添加项存储到数组中

时间:2016-05-12 17:19:52

标签: php arrays

我正在尝试使用TMDB(电影数据库)API创建一个数组,我正在使用PHP的this包装器。

我正在尝试这样做

require_once('../classes/tmdb-api.php');

// if you have no $conf it uses the default config
$tmdb = new TMDB(); 

//Insert your API Key of TMDB
//Necessary if you use default conf
$tmdb->setAPIKey('myKEy');

//Title to search for
$title = $_POST['searchTerm'];
$movies = $tmdb->searchMovie($title);
// returns an array of Movie Object

$movieArray = array();
$movieSearchArray = array();

foreach($movies as $movie) {
    $movieTitle = $movie->getTitle();
    $movieSearchArray[$movieTitle] = ['ID'][$movie->getID()];
    $movieSearchArray[$movieTitle] = ['Trailer'][$movie->getTrailer()];
}

$movieArray[] = $movieSearchArray;

print_r($movieArray);

所以例如当用户搜索'Rocky'时它将带回多个不同的电影标题但是对于我想要创建像这样的数组的每个电影标题,我试图在foreach循环中执行此操作但是我做错了什么?

[Rocky] => (
   "id" = "2",
   "rating" = "4"
)

请记住,可能有10部不同的电影。这就是我现在搜索'Rocky'时返回的内容。

Array
(
    [0] => Array
        (
            [Rocky] => 
            [Rocky II] => 
            [Rocky IV] => 
            [Rocky V] => 
            [Rocky Balboa] => 
            [Rocky III] => 
            [Rocky VI] => 
            [Creed] => 
            [The Real Rocky] => 
            [Rocky Marciano] => 
            [Where is Rocky II?] => 
            [Rocky Handsome] => 
            [Rocky Road] => 
            [Rocky Mountain] => 
            [Rocky Pink] => 
            [Rocky and Bullwinkle] => 
            [The Rocky Horror Picture Show] => 
            [Rocky Mountain Grandeur] => 
        )

)

1 个答案:

答案 0 :(得分:2)

我想你可以做到这一点,除了将项目分配给数组之外,[]中的索引必须在等于(=)符号之前,或者你必须为整个数组分配键和值。

所以

foreach($movies as $movie) {
    $movieTitle = $movie->getTitle();
    $movieSearchArray[$movieTitle]['ID'] = $movie->getID();
    $movieSearchArray[$movieTitle]['Trailer'] = $movie->getTrailer(); 
}

foreach($movies as $movie) {
    $movieSearchArray[$movie->getTitle()] = array(
        'ID' => $movie->getID(),
        'Trailer' => $movie->getTrailer()
    );
}

以及$ movie对象中的其他数据