搜尋

首頁  >  問答  >  主體

求解數組的列數

<p>在這個陣列輸出中,我如何計算類型的數量?或者更好的是,如何在計算時排除additional_data? </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>嘗試過 <code>count(array_column($swatchLists, 'type'));</code></p> <p>但輸出為0</p>
P粉818317410P粉818317410531 天前621

全部回覆(1)我來回復

  • P粉060112396

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

    請嘗試以下程式碼

    $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);

    每種類型的計數都會儲存在$countResult中,陣列鍵是類型值,陣列值是計數。

    回覆
    0
  • 取消回覆