2

我如何组合两个数组,它应该像下面的例子一样排序?

我想拿这几个数组:

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
        )

)

我希望它应该是这样的:

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
        )

)

我试图做一些循环,但没有结果,请帮忙

谢谢

4

2 回答 2

2

像这样的东西...

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

不确定您希望生成的数组是什么样子,但这里是$search一个数组示例:

 $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);
于 2012-06-07T01:10:08.800 回答
1
$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);
于 2012-06-07T00:57:02.477 回答