Hello. There is an array

[anatolypower-pamir2] => Array ( [0] => Array ( [id] => 64 [to_user] => anatolypower [from_user] => pamir2 [message] => rrtt [status] => 1 [send_date] => 2017-09-05 14:07:56 ) [1] => Array ( [id] => 69 [to_user] => pamir2 [from_user] => anatolypower [message] => Что такое rrtt ? [status] => 1 [send_date] => 2017-09-05 14:14:47 ) [2] => Array ( [id] => 72 [to_user] => anatolypower [from_user] => pamir2 [message] => Привет :) [status] => 1 [send_date] => 2017-09-05 18:00:21 ) [3] => Array ( [id] => 73 [to_user] => pamir2 [from_user] => anatolypower [message] => Получил твое сообщение [status] => 1 [send_date] => 2017-09-05 18:00:37 ) ) 

How to count how many matches there where [status] => 1 and [to_user] => pamir2

  • Does this concern the same question of getting the last message in a group instead of the first one when GROUP BY? Yesterday I changed one of the answers to your questions and added the necessary SQL there. All this is done by any perversions on the side of the database. If you have a million messages in the database, will you also read it in the array? - user239133
  • With GROUP BY, solve everything very simply, create an array of user dialogs and output. Everything works great. Now I want to count the number of incoming and outgoing messages. But it seems to have solved the problem. But so far only in thoughts. Now the code is collected and tested. If everything is OK, but according to logic it should be beaten, then I delete this question. - Tokwiro
  • Here is the query for that first question: SELECT m1.*, (SELECT COUNT(*) FROM messages WHERE to_send = m1.to_send) cnt FROM messages m1 LEFT JOIN messages m2 ON m1.to_send = m2.to_send AND m1.id < m2.id WHERE m2.id IS NULL; - user239133
  • For this question, too, everything must be decided on the side of the database. It’s wrong to handle an array on the PHP side in general. Learn SQL or PDO. Serious projects are being done at MVC, where M (odel) is the hardest and most important part, and it also works with the base. - user239133

2 answers 2

 for ($i=0; $i < count($data); $i++) { if($data[$i]['status'] == 1) $a++; } echo $a; 

Where $ data is an array variable. Other data can be calculated by analogy with an example.

  • And I wanted to make $ sum = 0; foreach ($ data [$ dialogname] as $ item) {$ sum + = (float) $ item ['status']; } echo $ sum; - Tokwiro

If I understand the essence of the problem, then you can bypass an array of any depth using array_walk_recursive()

 echo findMatches($arr, 'status', 1); function findMatches($arr, $key, $val) { array_walk_recursive($arr, function ($i, $k) use (&$count, $key, $val) { !($k == $key && $i == $val) ?: ++$count; }); return (!empty($count) ? $count : 0); } 
  • @Tokwiro added a wrapper for convenient use. - Edward