简体   繁体   中英

Create multidimentional array from two arrays

I have two arrays :

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' ));

This is an array of categories groups I have in the other side an array of categories :

$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' 
    )
);

What i want is :

$result = array (
  'INFORMATIQUE ET MULTIMEDIA' => 
    array (
      1 => string 'Téléphones',
      2 => string 'Tablette'
    )
  'VEHICULES' => 
    array (
      4 => string 'Motos',
      4 => string 'Motos'
    )
);

This is my code but it doesn't work but the problem is that it records a single line :

    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 ++;
            }
        }
    }

try this code, it will work for you

<?php
$result = null;
foreach($goups as $key => $value)
    foreach($categories as $categorie)
        if(  $key == $categorie['groupid'] )
            $result[$value][] = $categorie['name']

?>

You got most of the code right, but you keep assigning all your data in the first index of your sub-array, which is why you get one single result. Try the code below

foreach($groups as $id => $name)
{
    $n = 1;
    foreach($categories as $k=>$v)
    {
        if($v['groupid'] == $id){
            $result[$name][$n] = $['name'];
            $n++;
        }
    }
}
foreach($groups as $id => $name)
{
    foreach($categories as $k=>$v)
    {
        if($v['groupid'] == $id){
            $result[$name][] = array($v['id'] => $v['name']);
        }
    }
}

or a simple one.

    foreach($categories as $k=>$v)
    {
        $result[$groups[$v['groupid']]][] = array($v['id'] => $v['name']);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM