S
S
Stadinov Denis2015-02-12 17:57:03
PHP
Stadinov Denis, 2015-02-12 17:57:03

Count duplicate values ​​in a variable?

Progans!
The question haunts me, I can’t figure out how I want to calculate the nested array.
There is an array

$arr[] = array ("name" => "Название 1", "length" => 100, "count" => 15);
$arr[] = array ("name" => "Название 2", "length" => 99,  "count" => 5);
$arr[] = array ("name" => "Название 3", "length" => 99,  "count" => 3);
$arr[] = array ("name" => "Название 4", "length" => 100, "count" => 25);

It is necessary to get an array at the output with a counted number (count) of equal lengths (length), but so that they do not repeat.
Those. So
array(
   array("length" => 100, "count" => 40)
   array("length" => 99,  "count" => 8)
)

I already asked this question , thanks to everyone who responded, but the answers do not quite match the question.
And my decision does not correspond to the Wishlist.
What am I missing?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yakhnenko, 2015-02-12
@StaDi

elementary

$arr = array();
$arr[] = array ("name" => "Название 1", "length" => 100, "count" => 15);
$arr[] = array ("name" => "Название 2", "length" => 99,  "count" => 5);
$arr[] = array ("name" => "Название 3", "length" => 99,  "count" => 3);
$arr[] = array ("name" => "Название 4", "length" => 100, "count" => 25);

$temp = array();
foreach ($arr as $item) {
  $temp[$item['length']] = isset($temp[$item['length']]) ?
    $temp[$item['length']] + $item['count'] :
    $item['count'];
}

$result = array();
foreach ($temp as $length => $count) {
  $result[] = array("length" => $length, "count" => $count);
}

print_r($result);

H
He11ion, 2015-02-12
@He11ion

How many phpshnik do not feed, but still the bike will write, instead of reading the manual.
array_count_values(array_column($arr, 'length'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question