I have an array like that:
(
(0) => Array
(
(uid) => '100',
(name) => 'Blue t-shirt 4 years',
(ean) => '123456'
),
(1) => Array
(
(uid) => '5465',
(name) => 'blue shirt 24 years',
(ean) => '123'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Shirt 4 Years',
(ean) => '12345'
)
);
I am trying to count how many entries in the array have all the words on the key name "shirt 4 years" case insensitive or have the same 'ean' number.
In that case would return 2. What's the best way to do that?
You can prepare regex that matches provided words in any order:
function words_regex(array $words) {
$regex = array_reduce($words, function($carry, $word) {
return $carry . '(?=.*\b' . preg_quote($word) . '\b)';
}, '/');
return $regex . '.*/i';
}
Having this function you can filter items and count them:
$regex = words_regex($words);
$count = count(array_filter($array, function($item) use ($regex) {
return preg_match($regex, $item['name']);
}));
Here is working demo.
Those are two different goals. The first one (count key name) is a simple foreach
loop
The second logic requires you to have an array of counter for each ean
, loop through the array and count each ean
into an array slot. Then you can loop through the array and find those that have count > 1
Combining the two through the same loop will work, but then you need to analyze the second condition.
You need to loop through the array and check one by one if there are matched string and count it to a variable..
<?php
$array = [
["uid"=>'100', 'name'=>'Blue t-shirt 4 years', 'ean'=>'123456'],
["uid"=>'5465', 'name'=>'blue shirt 24 years', 'ean'=>'123'],
["uid"=>'40489', 'name'=>'Shirt 4 Years', 'ean'=>'12345']
];
echo("It's ".countArrayVal($array, 'name', 'shirt 4 years'));
function countArrayVal($array, $key, $search){
$count = 0;
for ($i=0; $i < count($array); $i++) { //Loop
if(stripos($array[$i][$key], $search)!==false) //Check matched string
$count++; //Update the counter
}
return $count; //Return count
}