简体   繁体   中英

count number of value per id in array

I have this script in php i want to get the number of value in the table in below my script

$count = 0;
         
foreach ($info as $key => $value)
{
    foreach ($value as $c => $val)
    {
        var_dump($val) . "<br>";
                 
        if (strcmp($val,"Tankh ") == 0)
        {
            $count++;
            //echo $count;
        }
    }

    // die();
                      
    echo $count;
    return $count;

var_dump the $val :

string(9) "Nomclient" 
string(13) "Villeclient " 
string(7) "Mohamed" 
string(8) "Tankh " 
string(6) "Fatima" 
string(9) "Tankh " 
string(6) "Brahim" 
string(6) "Tankh " 
string(5) "Jamal" 
string(8) "Tankh " 
string(5) "Ikram" 
string(6) "Tankh " 
string(6) "Karima" 
string(5) "Rain"

thanks in advance

I think you'd want something like this... if I understand correctly:

$val_counts = array();

foreach ($info as $key => $value)
{
   foreach ($value as $c => $val)
   {
      $val_counts[$val]++;
   }
}

Perhaps you can leverage the existing function array_count_values<\/a> for every $value<\/code> instead of checking the individual values.

$info = [
    [
        "Nomclient", "Villeclient", "Mohamed", "Tankh", "Fatima", "Tankh", "Brahim", "Tankh", "Jamal", "Tankh", "Ikram", "Tankh", "Karima", "Rain"
    ]
];

$val_counts = array_map(function($value){
    return array_count_values($value);
}, $info);

print_r($val_counts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM