Asked  1 Year ago    Answers:  5   Viewed   20 times

Hi, How can we find the count of duplicate elements in a multidimensional array ?

I have an array like this

Array
(
    [0] => Array
        (
            [lid] => 192
            [lname] => sdsss
        )

    [1] => Array
        (
            [lid] => 202
            [lname] =>  testing
        )

    [2] => Array
        (
            [lid] => 192
            [lname] => sdsss
        )

    [3] => Array
        (
            [lid] => 202
            [lname] =>  testing
        )

)

How to find the count of each elements ?

i.e, count of entries with id 192,202 etc

 Answers

4

You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.

array_count_values(array_map(function($item) {
    return $item['lid'];
}, $arr);

Plus, it's a one-liner, thus adding to elite hacker status.

Update

Since 5.5 you can shorten it to:

array_count_values(array_column($arr, 'lid'));
Thursday, April 1, 2021
 
2

I updated your function and it is giving expected output. Please give a try as following.

function array_key_exists_r($needle, $haystack){
    $result = array_key_exists($needle, $haystack);
    if ($result) 
    {
        foreach ($haystack as $a=>$v) 
        {
            if($needle == $a)
                return $haystack[$a];
            if (is_array($v)) {
                $result = array_key_exists_r($needle, $v);
            }
            if ($result) return $result;
        }
    }
    foreach ($haystack as $v) {
        if (is_array($v)) {
            $result = array_key_exists_r($needle, $v);
        }
        if ($result) return $result;
    }
    return $result;
};
Thursday, April 1, 2021
2

The actual problem is you're not assigning the result of array_reverse to anything

// change this
array_reverse($respArr);

// to this
$respArr = array_reverse($respArr);
Saturday, May 29, 2021
 
5
//Assumption: Input is in $in

//Step 1: Cumulate
$tmp=array();
foreach ($in as $skill) {
  if (isset($tmp[$skill['skill_name']]))
    $tmp[$skill['skill_name']][]=$skill['feed_id'];
  else
    $tmp[$skill['skill_name']]=array($skill['feed_id']);
}

//Step 2: Fix up desired output format
$out=array();
foreach ($tmp as $k=>$v)
  $out[]=array(
    'skill_name' => $k,
    'feed_id' => implode(', ', $v),
    'count' => sizeof($v)
  );

//Result is in $out
Saturday, May 29, 2021
 
5

Use anonymous functions:

for ($i = 0; $i < count($tables); $i++) {
    $tables[$i]['form'] = function() {
        ...
    };
}

Then you call one of the functions as:

$tables[$i]['form']();
Saturday, May 29, 2021
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :