Php SQL-按关联值分隔结果?
在做任何事情之前,我先让你看看我的桌子: (在PHP的上下文中)Php SQL-按关联值分隔结果?,php,mysql,Php,Mysql,在做任何事情之前,我先让你看看我的桌子: (在PHP的上下文中) 我想通过一个查询创建一个多维数组,这样一组具有相同id的标记将在相同的位置结束: <?php // Given the above example table, it would essentially produce this: $my_1 = array ( array('ect'), array('123', 'tag'),
我想通过一个查询创建一个多维数组,这样一组具有相同id的标记将在相同的位置结束:
<?php
// Given the above example table, it would essentially produce this:
$my_1 = array
( array('ect'),
array('123', 'tag'),
array('lolly', 'hat')
);
使用二维数组:
$array = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$tag = $row['tag'];
if (isset($array[$id])) {
$array[$id][] = $tag;
} else {
$array[$id] = array($tag);
}
}
生成的$array
将
array(1 => array('ect'),
7 => array('123', 'tag'),
9 => array('lolly', 'hat'))
不要使用单独的变量,使用二维数组。
<?php
$array = array();
foreach($tags as $tag)
{
if(array_key_exist($tag->id,$array)){
//if key is assigned in array, we can push value to key
$array[$tag->id] = array_push($tag->value,$array[$tag->id]);
}else{
//if key is not assigned we will create key and push value
$array[$tag->id] = $tag->value;
}
}
//usage
print_r($array[7]); // list tags with id 7
?>