1

I have this php array named $ids:

Array ( 
     [0] => Array ( [id] => 10101101 ) 
     [1] => Array ( [id] => 18581768 ) 
     [2] => Array ( [id] => 55533322 ) 
     [3] => Array ( [id] => 55533322 ) 
     [4] => Array ( [id] => 64621412 )
)

And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.

Something like this:

$newArr = array(
    10101101 => 1,
    18581768 => 1,
    55533322 => 2,
    64621412 => 1,
);

This is what I have:

$newArr = array();
$aux1 = "";

//$arr is the original array
for($i=0; $i<count($arr); $i++){
    $val = $arr[$i]["id"];
    if($val != $aux1){
        $newArr[$val] = count(array_keys($arr, $val));
        $aux1 = $val;
    }
}

I supose array_keys doesn't work here because $arr has the id values in the second dimension.

So, how can I make this work?

Sorry for my bad english and thanks.

LF00
  • 27,015
  • 29
  • 156
  • 295

3 Answers3

5

array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.

$newArr = array_count_values(array_column($ids, 'id'));
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Or do it by hand like this where $arr is your source array and $sums is your result array.

$sums = array();
foreach($arr as $vv){
    $v = $vv["id"];
    If(!array_key_exists($v,$sums){
        $sums[$v] = 0;
    }
    $sums[$v]++;
}
steven
  • 4,868
  • 2
  • 28
  • 58
0

You can traverse your array, and sum the id appearance, live demo.

$counts = [];
foreach($array as $v)
{
  @$counts[$v['id']] += 1;
}
print_r($counts);
LF00
  • 27,015
  • 29
  • 156
  • 295