thegrede
thegrede

Reputation: 494

Combine but skip array values in PHP

How can I combine two arrays it should be ordered like the example below?

I want to take this few arrays:

Array
(
    [0] => Array
        (
            [0] => ZE
            [1] => CD
            [2] => 97
        )

    [1] => Array
        (
            [0] => ZE
            [1] => CD
            [2] => 1908923
        )

    [2] => Array
        (
            [0] => ZD
            [1] => CD
            [2] => 23
        )

)

And I want it should be like this:

Array
(
    [0] => Array
        (
            [ZE] => Array
                (
                    [0] => Array
                        (
                            [0] => CD
                            [1] => 97
                        )

                    [1] => Array
                        (
                            [0] => CD
                            [1] => 1908923
                        )
                )
        )

    [1] => Array
        (
            [0] => ZD
            [1] => CD
            [2] => 23
        )

)

I tried to do some loops but I got no result, please help

Thanks

Upvotes: 2

Views: 192

Answers (2)

Sam
Sam

Reputation: 2970

$array = array(
  array(
    "ZE",
    "CD",
    97
  ),
  array(
    "ZE",
    "CD",
    1908923
  ),
  array(
    "ZD",
    "CD",
    23
  )
);

$new_array = array();
$i = 0;
$ix = 1;
foreach($array as $var){
  if($var[0]=='ZE'){
    $new_array[0]['ZE'][$i][0] = 'CD';
    $new_array[0]['ZE'][$i][1] = $var[2];
    $i++;
  }else{ 
    $new_array[$ix][0] = 'ZD';
    $new_array[$ix][1] = 'CD';
    $new_array[$ix][2] = $var[2];
    $ix++;
  }
}

var_dump($new_array);

Upvotes: 1

keithhatfield
keithhatfield

Reputation: 3273

Something like this ...

$array = array(
    array(
        "ZE",
        "CD",
        97
    ),
    array(
        "ZE",
        "CD",
        1908923
       ),
    array(
        "ZD",
        "CD",
        23
    )
 );

 $result = array();
 $search = 'ZE';

 foreach($array as $elem){
     if(($key = array_search($search, $elem)) !== false){
         unset($elem[$key]);
         $result[0][$search][] = $elem;
     } else {
         $result[] = $elem;
     }
 }

 print_r($result);

Not sure exactly what you want the resulting array to look like, but here is an example with $search being an array:

 $result = array();
 $search = array('ZE', 'ZD', 'ZI');

 foreach($array as $elem){
     $key = false;
     foreach($search as $s){
         if(($key = array_search($s, $elem)) !== false){
             break;
         }
     }
     if($key !== false){
         unset($elem[$key]);
         $result[0][$s][] = $elem;
     } else {
         $result[] = $elem;
     }
 }

 print_r($result);

Upvotes: 2

Related Questions