skip to Main Content

In this array output, how can I count the type column? Or better, how can I exclude the addition_data when counting it? Answer should be 3 since there are only 3 type column

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} )

Tried
count(array_column($swatchLists, 'type'));

But it’s outputting 0

2

Answers


  1. Please try this code

    $countResult = array();
    
    foreach( $swatchLists as $item ){
        if( isset($item['type']) == false ){
            continue; // excluding the array which does NOT contains the 'type'
        }
        $type = $item['type'];
        if( isset($countResult[$type]) ){
            $countResult[$type]++;
        }else{
            $countResult[$type] = 1;
        }
    }
    var_dump($countResult);
    

    every types of count will be store into $countResult, the array-key is the type value, the array-value is the count.

    Login or Signup to reply.
  2. One way would be to filter out the items with array_filter:

    $input = [
      124               => [ 'type' => 0, 'value' => '4 Pack', 'label' => '4 Pack' ],
      125               => [ 'type' => 0, 'value' => '6 Pack', 'label' => '6 Pack' ],
      126               => [ '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}'
    ];
    
    $items = array_filter(
      $input,
      fn($value, $key) => is_int($key) && array_key_exists('type', $value),
      ARRAY_FILTER_USE_BOTH
    );
    
    echo count($items);   // Output: 3
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search