如何从多维数组中获取具有重复次数的值和键

时间:2019-04-16 10:40:25

标签: arraylist

我在PHP中有一个多维数组,并且id中有重复项,如何获得重复数和名称?

$myArray['names'] = array(
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"13" , "name"=>"Omar"),
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"13" , "name"=>"Omar"),
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"13" , "name"=>"Omar"),
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"12", "name"=>"Ahmed" )
);

我想让它看起来像这个数组     需要它

$array = ("id"=>"12", "name"=>"ahmed", "Count"=>"5")

1 个答案:

答案 0 :(得分:0)

您可以使用foreach循环完成操作,如下所示:

$myArray['names'] = array(
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"13" , "name"=>"Omar"),
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"13" , "name"=>"Omar"),
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"13" , "name"=>"Omar"),
    array( "id"=>"12", "name"=>"Ahmed" ),
    array( "id"=>"12", "name"=>"Ahmed" )
);

$remove_duplication = array();
$key_exist = array();
foreach( $myArray as $row ) {
    foreach ( $row as $item ) {
        if ( in_array( $item["id"], $key_exist ) ) {
            $remove_duplication[$item["id"]]["Count"] = $remove_duplication[$item["id"]]["Count"] + 1;
        } else {
            $key_exist[] = $item["id"];
            $remove_duplication[$item["id"]] = $item;
            $remove_duplication[$item["id"]]["Count"] = 1;
        }

    }
}
print'Removed Duplication: <pre>';
print_r($remove_duplication);
print'</pre>';

$rearrange_array = array();
foreach ( $remove_duplication as $key => $value ) {
  $rearrange_array[] = $value;
}
print'Arrange array with 0: <pre>';
print_r($rearrange_array);
print'</pre>';