2
回答
php数组处理,新数组组成
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   
$arr = array(
    '45' => array(
            'gid' => '1',
            'id' => '45',
            'name' => 'aa',
        ),

    '46' => Array(
            'gid' => '1',
            'id' => '46',
            'name' => 'gg',
        ),

    '42' => Array(
            'gid' => '2',
            'id' => '42',
            'name' => 'bb',
        ),

    '41' => Array(
            'gid' => '2',
            'id' => '41',
            'name' => 'cc',
        )

);

//怎么将该数组 根据键值中的'gid'的值来归类数组,把所有'gid'='1' 的数组拼成一个新的数组,
//'gid'='2'的数组拼成一个新数组
//处理后的结果为两个新数组:$arr1,$arr2

如:

$arr1 = array(

    '45' => array(
            'gid' => '1',
            'id' => '45',
            'name' => 'aa',
        ),

    '46' => Array(
            'gid' => '1',
            'id' => '46',
            'name' => 'gg',
        ),

);

$arr2=array(
    '42' => Array(
            'gid' => '2',
            'id' => '42',
            'name' => 'bb',
        ),

    '41' => Array(
            'gid' => '2',
            'id' => '41',
            'name' => 'cc',
        )

);

//求处理方法

PHP
举报
忧桑
发帖于5年前 2回/549阅
共有2个答案 最后回答: 5年前
<?php
$arr = array( 
    '45' => array( 
            'gid' => '1', 
            'id' => '45', 
            'name' => 'aa', 
        ), 

    '46' => Array( 
            'gid' => '1', 
            'id' => '46', 
            'name' => 'gg', 
        ), 

    '42' => Array( 
            'gid' => '2', 
            'id' => '42', 
            'name' => 'bb', 
        ), 

    '41' => Array( 
            'gid' => '2', 
            'id' => '41', 
            'name' => 'cc', 
        ) 
);
foreach($arr as $k=>$v){
	$data[$v['gid']][$k]=$v;
}
$arr1=$data[1];
$arr2=$data[2];
var_dump($arr1);
var_dump($arr2);
?>


输出:



array(2) {
  [45]=>
  array(3) {
    ["gid"]=>
    string(1) "1"
    ["id"]=>
    string(2) "45"
    ["name"]=>
    string(2) "aa"
  }
  [46]=>
  array(3) {
    ["gid"]=>
    string(1) "1"
    ["id"]=>
    string(2) "46"
    ["name"]=>
    string(2) "gg"
  }
}
array(2) {
  [42]=>
  array(3) {
    ["gid"]=>
    string(1) "2"
    ["id"]=>
    string(2) "42"
    ["name"]=>
    string(2) "bb"
  }
  [41]=>
  array(3) {
    ["gid"]=>
    string(1) "2"
    ["id"]=>
    string(2) "41"
    ["name"]=>
    string(2) "cc"
  }
}


顶部