skip to Main Content

I have 2 array like

array (
  0 => 'END PIECE',
  1 => 'END PIECE',
  2 => 'END PIECE',
  3 => 'Title translation test 2',
  4 => 'Title translation test 2',
  5 => 'PIÈCE D'EXTRÉMITÉ'
);

and

array (
  0 => '47933',
  1 => '47935',
  2 => '47936',
  3 => '47929',
  4 => '47930',
  5 => '47933'
);

I want to make ONE array from this 2 array like

array (
  'END PIECE' => '47933',
  'END PIECE' => '47935',
  'END PIECE' => '47936',
  'Title translation test' => '47929',
  'Title translation test' => '47930',
  'PIÈCE D'EXTRÉMITÉ' => '47933'
);

Is it possible? PHP 5.3 version required, I have tried this

$c = array();
foreach($arr1 as $k => $val){
    $c[] = array($arr2[$k] => $val);
}

But it not works

2

Answers


  1. You can use array_combine() function it is working (PHP 5, PHP 7) like the following

    $a = array('green', 'red', 'yellow');
    $b = array('avocado', 'apple', 'banana');
    $c = array_combine($a, $b);
    
    print_r($c);
    

    Output :

    Array
    (
        [green]  => avocado
        [red]    => apple
        [yellow] => banana
    )
    
    Login or Signup to reply.
  2. There are two ways to do this, the simple version will always have a subarray…

    $c = array();
    foreach($arr1 as $k => $val){
        $c[$arr2[$k]][] = $val;
    }
    
    print_r($c);
    

    gives…

    Array
    (
        [END PIECE] => Array
            (
                [0] => 47933
                [1] => 47935
                [2] => 47936
            )
    
        [Title translation test 2] => Array
            (
                [0] => 47929
                [1] => 47930
            )
    
        [PIÈCE D'EXTRÉMITÉ] => Array
            (
                [0] => 47933
            )
    
    )
    

    If you only want duplicates to have sub arrays, then you need to check when adding a new item if the item is already set and already an array, adjusting as you go along…

    $c = array();
    foreach($arr1 as $k => $val){
        if ( isset ($c[$arr2[$k]])) {
            if ( !is_array($c[$arr2[$k]]) )
                $c[$arr2[$k]] = [$c[$arr2[$k]]];
            $c[$arr2[$k]][] = $val;
        }
        else    {
            $c[$arr2[$k]] = $val;
        }
    }
    print_r($c);
    

    gives…

    Array
    (
        [END PIECE] => Array
            (
                [0] => 47933
                [1] => 47935
                [2] => 47936
            )
    
        [Title translation test 2] => Array
            (
                [0] => 47929
                [1] => 47930
            )
    
        [PIÈCE D'EXTRÉMITÉ] => 47933
    )
    

    As you can see, the PIÈCE D’EXTRÉMITÉ element is different in both cases.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search