PHP count null or 'new' elements within array - php

My array is below. What I am trying to do is count the number of nodes in the array have null or 'new' for read_status.
Is there something more sufficient than looping through the array?
Array
(
[0] => Array
(
[id] => 428
[read_status] =>
)
[1] => Array
(
[id] => 427
[read_status] =>
)
[2] => Array
(
[id] => 441
[read_status] => new
)
[3] => Array
(
[id] => 341
[read_status] => read
)
)
So the count should be 3.

you could do
$count = count(array_filter($myArray, function($item){
return $item['read_status'] != 'new';
}));
echo $count;
but I think its more efficient to just loop through it like this:
$count = 0;
foreach($myArray as $item){
if($item['read_status'] != 'new')$count++;
}
echo $count;

There is nothing wrong with looping in the array to do this, it might actually be faster than using a generic method to do it for you. It's simply this :
$count = 0;
foreach ($arrays as $entry)
{
if (!$entry['read_status'] || $entry['read_status'] === "new")
{
$count++;
}
}
echo $count;

I actually improved my SQL by removing the null completely -- so now read_status is either read or new.
IF(feed_read.read_status IS NULL,'new','read') AS read_status
From there, I was able to utilize another SO question in order to count the 'new' elements.
$counted = array_count_values(array_map(function($value){return $value['read_status'];}, $result));
echo $counted['new'];

Related

How can I filter a multidimentional array for duplicates?

I have an array set up like:
Array (
[0] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe500303 )
[1] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe600303 )
[2] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe700303 )
[3] => Array ( [stage] => biometrics [applicant_id] => b79a4c6ea30611e3a3160675fe800303 )
[4] => Array ( [stage] => biometrics_queue [applicant_id] => b79a4c6ea30611e3a3160675fe900303 )
)
First, I want to check to see if there are any duplicate applicant_id's then I need to check the stages for the duplicates. If the applicant_id are the same, but stages are different, they are ok, If the applicant_id's are the same and stages are either the same (biometrics & biometrics) or if it is (biometrics and biometrics_queue) I need to delete that entry from the array.
Not sure how to do this.
.
So here is what I have so far. It works, but there are a lot of loops going on, don't wanna end up using too many resources or getting into an infinite loop...Does anyone see anything wrong with what I'm doing?
First, I used a function called convert stages, so that if there is anything that is a stage name and then _queue appended to the end, it changes it to just the stage name.
foreach ($timer_entry as $key => $value){
$timer_entry[$key]['stage'] = convert_stages($timer_entry[$key]['stage']);
}
Then I have a foreach inside of a for, checking for applicant_id's that might be the same:
for ($i = 0; $i < count($timer_entry); $i++) {
foreach ($timer_entry as $key => $value){
if ($key == $i) {
continue;
}
else {
if ($timer_entry[$key]['applicant_id'] == $timer_entry[$i]['applicant_id']) {
if ($timer_entry[$key]['stage'] == $timer_entry[$i]['stage']) {
unset($timer_entry[$key]);
}
}
}
}
}
If they are the same, I unset them.
I didn't test it, but I think this might do the trick:
$array = array_map('unserialize', array_unique(array_map('serialize', $array)));
How about:
foreach( $myArray as $index => $element )
if (isset($tmp[$element['applicant_id']][str_replace('_queue','',$element['stage'])])
unset($myArray[$index]);
else
$tmp[$element['applicant_id']][str_replace('_queue','',$element['stage'])] = true;

Replace value in array based on other array

I would like to replace the value of a multidimensional array if a corrosponding array contains a certain value.
Basically, I have two multidimensional arrays. One contains the actual data and the other contains a yes/no for whether the first array should be modified.
Is there any way to do this:
if optB[i][i] contains 'yes'
then opt[i][i] = '<strong>'.opt[i][i].'</strong>';
I'm lost as to whether this is even possible. Any help would be greatly appreciated -- thank you!
Thank you for the help so far. Here is the array:
[opt] => Array
(
[0] => Array
(
[0] => value1
[1] => value2
)
[1] => Array
(
[0] => value3
[1] => value4
)
)
[optB] => Array
(
[0] => Array
(
[0] => on
)
[1] => Array
(
[1] => on
)
)
Those are some interesting arrays because usually numeric arrays always have a 0. I imagine you may have some different key combination so I think this is the best "future-proof" method:
foreach ($optB as $i => $optB2) {
foreach ($optB2 as $j => $val) {
if ($val) {
$opt[$i][$j] = '<strong>' . $opt[$i][$j] . '</strong>';
}
}
}
It is possible. You can do this:
for ($i = 0; $i < count(opt); $i++) {
if ($optB[$i][$i] == "yes")
opt[$i][$i] = '<strong>'.opt[$i][$i].'</strong>';
}
It can be written like this:
if (strpos($optB[$i][$i], 'yes'))
$opt[$i][$i] = '<strong>'.$opt[$i][$i].'</strong>';
Something along these lines:
foreach ($opt as $i => &$arr) {
foreach ($arr as $j => &$val) {
if ($optB[$i][$j]) {
$val = "<strong>$val</strong>";
}
}
}
Modify as needed.

After deleting the particular multidimensional array element in PHP, the Next array elements are not positioning automatically

I've created the multidimensional array in the following format
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [1] => Array ( [id] => 9 [quantity] => 2 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
When I try to unset an particular array element based on id, after unset i'm getting the array like below.
Array ( [0] => Array ( [id] => 10 [quantity] => 3 ) [2] => Array ( [id] => 12 [quantity] => 4 ) )
The array element is getting unset, but the next array element doesn't move to the deleted array position.
For unset an array element, I'm using the following code.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
How to solve this issue? Please kindly help me to solve it.
Thanks in advance.
Well, if you want to maintain order, but just want to re-index the keys, you can use the array_values() function.
$i = 0;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
$match = true;
break;
}
$i++;
}
if($match == 'true'){
unset($cartdetails['products'][$i]);
}
array_values($cartdetails['products']);
Using unset doesn't alter the indexing of the Array. You probably want to use array_splice.
http://www.php.net/manual/en/function.array-splice.php
http://php.net/manual/en/function.unset.php
Why do you use $i++ to find an element to unset?
You can unset your element inside foreach loop:
foreach($cartdetails['products'] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}
// in your case array_values will "reindex" your array
array_values($cartdetails['products']);
Why don't you use this???
$id = 9;
foreach($cartdetails["products"] as $key => $item){
if ($item['id'] == $id) {
unset($cartdetails['products'][$key]);
break;
}
}

most common values in a multidemensional array

My question is maybe repetitive but I really find it hard. (I have read related topics)
This is the array :
Array
(
[0] => Array
(
[legend] => 38440
)
[1] => Array
(
[bestw] => 9765
)
[2] => Array
(
[fiuna] => 38779
)
[3] => Array
(
[adam] => 39011
)
[4] => Array
(
[adam] => 39011
)
[5] => Array
(
[adam] => 39011
)
)
I have tried many ways to handle this array and find out the most common value. The result I expect is "adam"
$countwin = array_count_values($winnernames);
$maxwin = max($countwin);
$mostwinner = array_keys($countswin, $maxwin);
EDIT : My array is like this array("A"=>"1" , "B"=>"2" , "A"=>"1") it should return A is the most common
How about iterating your array and counting the values you've got?
$occurences = array();
foreach ($data as $row) {
foreach ($row as $key => $score) {
if (empty($occurences[$key])) {
$occurences[$key] = 1;
} else {
$occurences[$key]++;
}
}
}
and then sorting that
arsort($occurences);
and grabbing the first element of the sorted array
$t = array_keys($occurences);
$winner = array_shift($occurences);
You may try this code. A brute force method indeed. But a quick search made me to find this an useful one:
function findDuplicates($data,$dupval) {
$nb= 0;
foreach($data as $key => $val)
if ($val==$dupval) $nb++;
return $nb;
}
EDIT : Sorry, I misinterpreted your question! But it might be the first hint of finding the one with maximum counter.

parsing out the last number of the post

Ok so i have a post that looks kind of this
[optional_premium_1] => Array
(
[0] => 61
)
[optional_premium_2] => Array
(
[0] => 55
)
[optional_premium_3] => Array
(
[0] => 55
)
[premium_1] => Array
(
[0] => 33
)
[premium_2] => Array
(
[0] => 36 )
[premium_3] => Array
(
[0] => 88 )
[premium_4] => Array
(
[0] => 51
)
how do i get the highest number out of the that. So for example, the optional "optional_premium_" highest is 3 and the "premium_" optional the highest is 4. How do i find the highest in this $_POST
You could use array_key_exists(), perhaps something like this:
function getHighest($variableNamePrefix, array $arrayToCheck) {
$continue = true;
$highest = 0;
while($continue) {
if (!array_key_exists($variableNamePrefix . "_" . ($highest + 1) , $arrayToCheck)) {
$continue = false;
} else {
highest++;
}
}
//If 0 is returned than nothing was set for $variableNamePrefix
return $highest;
}
$highestOptionalPremium = getHighest('optional_premium', $_POST);
$highestPremium = getHighest('premium', $_POST);
I have 1 question with 2 parts before I answer, and that is why are you using embedded arrays? Your post would be much simpler if you used a standard notation like:
$_POST['form_input_name'] = 'whatever';
unless you are specifically building this post with arrays for some reason. That way you could use the array key as the variable name and the array value normally.
So given:
$arr = array(
"optional_premium_1" => "61"
"optional_premium_2" => "55"
);
you could use
$key = array_keys($arr);
//gets the keys for that array
//then loop through get raw values
foreach($key as $val){
str_replace("optional_premium_", '', $val);
}
//then loop through again to compare each one
$highest = 0;
for each($key as $val){
if ((int)$val > $highest) $highest = (int)$val;
}
that should get you the highest one, but then you have to go back and compare them to do whatever your end plan for it was.
You could also break those into 2 separate arrays and assuming they are added in order just use end() http://php.net/manual/en/function.end.php
Loop through all POST array elements, pick out elements having key names matching "name_number" pattern and save the ones having the largest number portion of the key names. Here is a PHP script which does it:
<?php // test.php 20110428_0900
// Build temporary array to simulate $_POST
$TEMP_POST = array(
"optional_premium_1" => array(61),
"optional_premium_2" => array(55),
"optional_premium_3" => array(55),
"premium_1" => array(33),
"premium_2" => array(36),
"premium_3" => array(88),
"premium_4" => array(51),
);
$names = array(); // Array of POST variable names
// loop through all POST array elements
foreach ($TEMP_POST as $k => $v) {
// Process only elements with names matching "word_number" pattern.
if (preg_match('/^(\w+)_(\d+)$/', $k, $m)) {
$name = $m[1];
$number = (int)$m[2];
if (!isset($names[$name]))
{ // Add new POST var key name to names array
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
} elseif ($number > $names[$name]['max_num'])
{ // New largest number in key name.
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
}
}
}
print_r($names);
?>
Here is the output from the script:
Array
(
[optional_premium] => Array
(
[name] => optional_premium
[max_num] => 3
[key_name] => optional_premium_3
[value] => Array
(
[0] => 55
)
)
[premium] => Array
(
[name] => premium
[max_num] => 4
[key_name] => premium_4
[value] => Array
(
[0] => 51
)
)
)
Though ineffective, you could try something like
$largest = 0;
foreach($_POST as $key => $value)
{
$len = strlen("optional_premium_");
$num = substr($key, $len);
if($num > $largest)
$largest = $num;
}
print_r($largest);
The problem being that this will only work for one set of categories. It will most likely give errors throughout the script.
Ideally, you would want to reorganize your post, make each array be something like
[optional_premium_1] => Array
(
[0] => 61
["key"] => 1
)
[optional_premium_2] => Array
(
[0] => 61
["key"] => 2
)
Then just foreach and use $array["key"] to search.

Categories