我有两个数组:
groups = array (
array (1 => string 'INFORMATIQUE ET MULTIMEDIA'),
array (2 => string 'VEHICULES' ),
array (3 => string 'IMMOBILIER' ),
array (4 => string 'POUR LA MAISON ET JARDIN'),
array (5 => string 'HABILLEMENT ET BIEN ETRE'),
array (6 => string 'LOISIRS ET DIVERTISSEMENT'),
array (7 => string 'EMPLOI ET SERVICE' ),
array (8 => string 'ENTREPRISE' ),
array (9 => string 'AUTRES' ));
这是一个类别组的数组 我在另一边有一系列类别:
$categories = array (
array (
'id' => string '1' ,
'name' => string 'Téléphones' ,
'groupid' => string '1'
),
array (
'id' => string '2',
'name' => string 'Tablette' ,
'groupid' => string '1'
),
array (
'id' => string '3' ,
'name' => string 'Voitures' ,
'groupid' => string '2'
),
array (
'id' => string '4' ,
'name' => string 'Motos',
'groupid' => string '2'
)
);
我想要的是:
$result = array (
'INFORMATIQUE ET MULTIMEDIA' =>
array (
1 => string 'Téléphones',
2 => string 'Tablette'
)
'VEHICULES' =>
array (
4 => string 'Motos',
4 => string 'Motos'
)
);
这是我的代码,但它不起作用,但问题是它记录了一行:
foreach($groups as $id => $name)
{
$n = 1;
foreach($categories as $k=>$v)
{
if($v['groupid'] == $id){
$result[$name] = array_fill($v['id'], 1, $v['name']);
$n ++;
}
}
}
答案 0 :(得分:0)
试试这段代码,它会对你有用
<?php
$result = null;
foreach($goups as $key => $value)
foreach($categories as $categorie)
if( $key == $categorie['groupid'] )
$result[$value][] = $categorie['name']
?>
答案 1 :(得分:0)
您的大部分代码都是正确的,但您仍然会在子阵列的第一个索引中分配所有数据,这就是您获得单个结果的原因。请尝试以下代码
foreach($groups as $id => $name)
{
$n = 1;
foreach($categories as $k=>$v)
{
if($v['groupid'] == $id){
$result[$name][$n] = $['name'];
$n++;
}
}
}
答案 2 :(得分:0)
foreach($groups as $id => $name)
{
foreach($categories as $k=>$v)
{
if($v['groupid'] == $id){
$result[$name][] = array($v['id'] => $v['name']);
}
}
}
或简单的。
foreach($categories as $k=>$v)
{
$result[$groups[$v['groupid']]][] = array($v['id'] => $v['name']);
}