【发布时间】:2014-01-05 12:41:14
【问题描述】:
我是多维数组的新手,遇到了问题,无法解决问题。我一直在尝试转这个:
数组
(
[1] => 数组
(
[cat_id] => 1
[猫名] => Schilderijen
[cat_description] => Omschrijving bij schilderijen
[艺术家] => 数组
(
[艺术家 ID] => 1
[姓氏] => ..一些值
)
)
)
大批
(
[1] => 数组
(
[cat_id] => 1
[猫名] => Schilderijen
[cat_description] => Omschrijving bij schilderijen
[艺术家] => 数组
(
[艺术家 ID] => 4
[姓氏] => ..一些值
)
)
)
到这样的东西,所以我可以调用一个类别并在下面列出相关的艺术家:
大批 ( [1] => 数组 ( [cat_id] => 1 [猫名] => Schilderijen [cat_description] => Omschrijving bij schilderijen [艺术家] => 数组 ( [艺术家 ID] => 1 [姓氏] => ..一些值 [艺术家 ID] => 4 [姓氏] => ..一些值 ) ) )我正在使用以下代码:
$cat_id = 1;
$query = "SELECT * FROM `categorie_has_artists` ";
$query .= " JOIN `categories` ON categories.cat_id = categorie_has_artists.cat_id AND categorie_has_artists.cat_id = :cat_id";
$query .= " JOIN `artists` ON artists.artist_id = categorie_has_artists.artist_id";
$stmt = $dbh->prepare($query);
$stmt->bindParam(':cat_id', $cat_id, PDO::PARAM_INT);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$array[$row['cat_id']] = array('cat_id' => $row['cat_id'], 'cat_name' => $row['cat_name'], 'cat_description' => $row['cat_description'], 'artist' => array());
$array[$row['cat_id']]['artist'][] = array('artist_id'=>$row['artist_id'], 'lastName' => $row['lastName']);
}
【问题讨论】:
-
第一个数组应该在循环之外,第二个应该在循环中。使
$isSet = false;外循环然后内循环添加if(!$isSet) { firstArray...; $isSet = TRUE; } else { secondArray...; } -
你不应该有相同的数组键 (artist_id,lastName) 在同一个数组中具有不同的值。
标签: php mysql arrays multidimensional-array