简体   繁体   中英

How to get value count from multidimentional array? PHP / Laravel

I am trying to count values of this array:

array:5 [▼
 "layout/theme.liquid" => array:5 [▶]
 "sections/featured-product.liquid" => array:1 [▶]
 "sections/header.liquid" => array:2 [▶]
 "templates/article.liquid" => array:1 [▶]
 "templates/product.liquid" => array:1 [▶]
]

My goal is to count inside this array how many there are arrays? The answer is 10, but stuck on trying to write the code properly.

The array example is being shown by dd(count($jsonLdAssets));

use a foreach loop and count all of them:

$main_array => array:5 [▼
 "layout/theme.liquid" => array:5 [▶]
 "sections/featured-product.liquid" => array:1 [▶]
 "sections/header.liquid" => array:2 [▶]
 "templates/article.liquid" => array:1 [▶]
 "templates/product.liquid" => array:1 [▶]
];
$total_count=0;

foreach ($main_array as $arr) {
    $total_count+=count($arr);
}

dd($total_count);

 //output : 10

You can do this:

$countTotal = 0;

foreach ($jsonLdAssets as $asset) {
    $countTotal = $countTotal + count($asset);
}

dd($countTotal);

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