Home  >  Q&A  >  body text

Find the number of columns in an array

<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粉818317410P粉818317410452 days ago569

reply all(1)I'll reply

  • P粉060112396

    P粉0601123962023-08-15 09:36:30

    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.

    reply
    0
  • Cancelreply