简体   繁体   中英

Find out number of array occurrences in php

this answer maybe on google but i couldnt find it because i dont know the exact keywords for this. The situation is as follows. I have an array called $value that contains 2 types of arrays:

[12] => Array ( 
        [id] => phone 
        [class] => phone 
        [config] => Array ( 
                            [disabled] => 1 
                            [value] => 1
                )
) 

[46] => Array ( 
        [id] => email 
        [class] => email 
        [config] => Array ( 
                            [display_type] => disabled 
                            [value] => 1
                    )
)

As you may see, they are almost the same except for the fact that one contains an array called "disabled" and the other "display_type". What im trying to do is to count how many of each type i have. I tried with this:

foreach ( $value as $col ) {
    if ( $col->config == 'disabled' ) {
        $total_default++;
    } elseif ( $col->config == 'display_type' ) {
        $total_custom++;
    }
}

but didnt work. I know it must be very simple but i just cant figure it out.

Thank you.

$col is an array, not object.

foreach ($value as $col) {
  if (array_key_exists('disabled', $col['config'])) {
      $total_default++;
  } else if (array_key_exists('display_type', $col['config'])) {
      $total_custom++;
  }
}

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