Gregory Schultz
Gregory Schultz

Reputation: 844

How to count more than one items in array_column?

I asked a question called 'How to count items in an array that's in an array?' and now I need help on expanding from that question.

How do you count items in two arrays?

My array looks like this:

Array
(
[0] => Array
(
    [acf_fc_layout] => irl_today_website_entry
    [irl_today_website] => Array
        (
            [0] => Array
                ( data removed)

            [1] => Array
                ( data removed )
        )
)
[1] => Array
(
    [acf_fc_layout] => irl_today_social_entry
    [irl_today_social] => Array
        (
            [0] => Array
                ( data remove )
            [1] => Array
                ( data remove)
        )
)
)

And I use:

<?php $arrays = get_field('irl_today_entry');
$res = array_map(function($x) {
return count($x);
}, array_column($arrays, 'irl_today_website'));?>

to count items in [irl_today_social]. How do I count items in [irl_today_social] and [irl_today_website]?

I tried array_column($arrays, "irl_today_social", "irl_today_website") and it only counted items in [irl_today_social]

Upvotes: 0

Views: 120

Answers (1)

lovelace
lovelace

Reputation: 1205

array_map() can be fed multiple arrays to work with. The first array "irl_today_social" elements are referenced by $x, the second "irl_today_website" by $y in this case.

Use following:

$res = array_map(function($x, $y) {
    $soc = count($x);
    $web = count($y);
    return ['soc' => $soc, 'web' => $web];
}, array_column($arrays, "irl_today_social"), array_column($arrays, "irl_today_website"));

array_map() will return an array with the count for each - the result sample output:

Array
(
    [0] => Array
        (
            [soc] => 2
            [web] => 3
        )

)

demo

Upvotes: 1

Related Questions