Find the number of columns in an array
P粉818317410
P粉818317410 2023-08-14 11:01:59
0
1
571
<p>How do I count the number of types in this array output? Or better yet, how to exclude additional_data when calculating? </p> <pre class="brush:php;toolbar:false;">Array ( [124] => Array ( [type] => 0 [value] => 4 Pack [label] => 4 Pack ) [125] => Array ( [type] => 0 [value] => 6 Pack [label] => 6 Pack ) [126] => Array ( [type] => 0 [value] => 12 Pack [label] => 12 Pack ) [additional_data] => {"swatch_input_type":"text","update_product_preview_image":"1","use_product_image_for_swatch":0} )</pre> <p>Tried <code>count(array_column($swatchLists, 'type'));</code></p> <p>But the output is 0</p>
P粉818317410
P粉818317410

reply all(1)
P粉060112396

Please try the following code

$countResult = array();

foreach( $swatchLists as $item ){
    if( isset($item['type']) == false ){
        continue; // 排除不包含'type'的数组
    }
    $type = $item['type'];
    if( isset($countResult[$type]) ){
        $countResult[$type]++;
    }else{
        $countResult[$type] = 1;
    }
}
var_dump($countResult);

Each type of count will be stored in $countResult, where the array key is the type value and the array value is the count.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!