I have a nested array with valid numbers => data:-
$validData = array(array(1 => 'one data'),array(5 => '5 data'),array(15 => '15 data'),array(30 => 'thirty data'));
Let say I have a query value, $query = 14;
I want to first check if there's a 14, if not then go to the nearest option ABOVE.
I've been doing nearest item with max, array_keys and ranges. But, matching or going above for some reason I can't see the best way?
// in case your array keys are already sorted
$prevKey = key(current($validData));
foreach($validData as $data) {
$currentKey = key($data);
if ($currentKey == $query) {
// found !
echo $currentKey;
break;
}
else if ($currentKey > $query) {
echo $currentKey;
break;
}
$prevKey = $currentKey;
}
Assuming the array is sorted
$query = 14;
$arrayThatWeWant = null;
foreach ( $validData as $index=>$vdSubRay)
{
$ak = key($vsSubRay);
if ( $ak == $query )
{
$arrayThatWeWant = $vdSubRay;
break;
}
else if ( $ak > $query )
{
$arrayThatWeWant = $validData[$index-1];
break;
}
}
Related
I need to compare an array that comes from a query, with a base array where I have the values that could have the array that comes from the query, the question is how to go through and compare the two arrays so that I get zero where the values do not match And give me the value of the array ?.
this is my code:
public function age_range_men()
{
$type = 'brands';
$id_array= 75;
$date_start= '2017-01-02 00:01:00';
$date_end='2017-03-31 23:59:59';
$datos = $this->statistics_model->range_age_men($type, $id_array, $date_start, $date_end);
$result = array();
foreach($datos as $dato) {
$result[] = array((string)$dato->rango, (int)$dato->conexiones );
}
$base= array(array('12 a 17'), array('18 a 24'),array('25 a 34'), array('35 a 44'), array('45 a 54'),array('55 a 64'),array('mas de 65'));
$res = array();
foreach ($base as $base1) {
// print_r($base1[0]);
// echo "<br>";
foreach ($result as $result2){
if ($base1[0] == $result2[0]){
}else{
echo 0;
break;
}
}
}
}
[The first line is $result and the second line is $base][1]
[1]: https://i.stack.imgur.com/LC5Ps.jpg
Here is my suggestion. Create an associative array for results. Make $base a list of keys rather than a strange multi-dimensional array. Check for the key in an array. I have the else echo 0 I have no idea what you want if it exists.
<?php
function age_range_men(){
$type = 'brands';
$id_array= 75;
$date_start= '2017-01-02 00:01:00';
$date_end='2017-03-31 23:59:59';
$datos = $this->statistics_model->range_age_men($type, $id_array, $date_start, $date_end);
$result = array();
foreach($datos as $dato) {
$result[(string)$dato->rango] = (int)$dato->conexiones; // Note this is now using a key
}
//This is no longer a multi-dimensional array just the keys we need
$base= array('12 a 17', '18 a 24','25 a 34', '35 a 44', '45 a 54','55 a 64','mas de 65');
$res = array();
foreach ($base as $key) {
if(array_key_exists($key, $results)){
//CODE???
} else {
echo 0;
}
}
}
age_range_men();
I have an array like this
Array ( [12313] => 1 [12312] => 1 ) 1
The array keys are the items that exist in the warehouse and values are the number of items.
I would like to check if the items and amounts actually exist in the warehouse database using php. I thought maybe I could use a foreach for each item check but I don't know how to use foreach. I would like to make a query like:
$query=$this->db->query("SELECT COUNT(*) as amount FROM warehouse where item=12313");
$check=$query->row_array();
$amt=$check['amount'];
if($amt>0){
return true;
}
else{
return false;
}
$array=array ( '12313' => 1,'12312' => 1 );
foreach($array as $k=>$val)
{
$query=$this->db->query("SELECT COUNT(*) as amount FROM warehouse where item='".$k."'");
$check=$query->row_array();
$amt=$check['amount'];
if($amt>0){
return true;
}
else{
return false;
}
}
Are you looking for something like:
$items = array(
12313 => 1,
12312 => 1,
);
foreach ( $items as $key => $value ) : //iterate over array
$query = "SELECT COUNT(*) as amount FROM warehouse where item = $key";
$check = $query->row_array();
$amt = $check['amount'];
if( $amt>0 ) {
return true;
}
else {
return false;
}
endforeach;
try this
$arr = array("[12313]" => "1" ,"[12312]" => "2");
foreach ($arr as $key=>$value) {
$query="SELECT COUNT(*) as amount FROM warehouse where item='".$key."'";
$check=$query->row_array();
$amt=$check['amount'];
if($amt>0){
return true;
}
else{
return false;
}
}
$array = array('12313' => 1, '12312' => 1);
foreach ($array as $key => $value) {
$this->db->select('COUNT(*) as amount');
$this->db->from('warehouse');
$this->db->where('item', $key);
$result = $this->db->get()->row_array();
return ($result['amount'] >= $value) ? TRUE : FALSE; //match no of items
// return ($result['amount'] > 0) ? TRUE : FALSE; //OR if just check the count
}
I have an array which comes from a report.
This report has info similar to:
157479877294,OBSOLETE_ORDER,obelisk,19/01/2013 01:42pm
191532426695,WRONG_PERFORMANCE,g3t1,19/01/2013 01:56pm
159523681637,WRONG_PERFORMANCE,g3t1,19/01/2013 01:57pm
176481653889,WRONG_PERFORMANCE,g4t1,19/01/2013 01:57pm
167479810401,WRONG_PERFORMANCE,g4t1,19/01/2013 02:00pm
172485359309,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
125485358802,WRONG_PERFORMANCE,g4t2,19/01/2013 02:02pm
172485359309,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
125485358802,DAY_LIMIT_EXCEEDED,obelisk,19/01/2013 02:03pm
What I need to do is get the total of each type of error and the location so for the first would be error: 'OBSOLETE_ORDER' and location: 'obelisk'. I have tried to do this a number of ways but the best I can come up with is a multi dimensional array:
$error_handle = fopen("$reportUrl", "r");
while (!feof($error_handle) )
{
$line_of_text = fgetcsv($error_handle, 1024);
$errorName = $line_of_text[1];
$scannerName = $line_of_text[2];
if($errorName != "SCAN_RESULT" && $errorName != "" && $scannerName != "SCAN_LOGIN" && $scannerName != "")
{
$errorsArray["$errorName"]["$scannerName"]++;
}
}
fclose($error_handle);
print_r($errorsArray);
gives me the following:
Array ( [OBSOLETE_ORDER] => Array ( [obelisk] => 1 ) [WRONG_PERFORMANCE] => Array ( [g3t1] => 2 [g4t1] => 2 [g4t2] => 2 ) [DAY_LIMIT_EXCEEDED] => Array ( [obelisk] => 2 ) )
which is great...except how do I then take that apart to add to my sql database?! (I am interested in getting the key and total of that key under the key the array is under)
and then add it to the tables
-errors-
(index)id_errors
id_event
id_access_scanner
id_errors_type
total_errors
-errors_type-
(index)id_errors_type
name_errors_type
-access_scanner-
(index)id_access_scanner
id_portal
name_access_scanner
PLEASE HELP!
Thanks!
A multidimensional array is more than you need. The approach to take is to create your own string ($arrayKey in my example) to use as an array key that combines the scanner name and the error so that you can get a count.
//this is the array containing all the report lines, each as an array
$lines_of_text;
//this is going to be our output array
$errorScannerArray = array();
//this variable holds the array key that we're going to generate from each line
$arrayKey = null;
foreach($lines_of_text as $line_of_text)
{
//the array key is a combination of the scanner name and the error name
//the tilde is included to attempt to prevent possible (rare) collisions
$arrayKey = trim($line_of_text[1]).'~'.trim($line_of_text[2]);
//if the array key exists, increase the count by 1
//if it doesn't exist, set the count to 1
if(array_key_exists($arrayKey, $errorScannerArray))
{
$errorScannerArray[$arrayKey]++;
}
else
{
$errorScannerArray[$arrayKey] = 1;
}
}
//clean up
unset($line_of_text);
unset($arrayKey);
unset($lines_of_text);
//displaying the result
foreach($errorScannerArray as $errorScanner => $count)
{
//we can explode the string hash to get the separate error and scanner names
$names = explode('~', $errorScanner);
$errorName = $names[0];
$scannerName = $names[1];
echo 'Scanner '.$scannerName.' experienced error '.$errorName.' '.$count.' times'."\n";
}
$list = array();
foreach ($lines as $line) {
$values = explode(',' $line);
$error = $values[1];
$scanner = $values[2];
if (!isset($list[$error])) {
$list[$error] = array();
}
if (!isset($list[$error][$scanner])) {
$list[$error][$scanner] = 1;
} else {
$list[$error][$scanner]++;
}
}
To go through each result I just did the following:
foreach ($errorsArray as $errorName=>$info)
{
foreach ($info as $scannerName=>$total)
{
print "$errorName -> $scannerName = $total </br>";
}
}
and now will just connect it to the sql
With your edited question, this much simpler loop will work for you, you just need to then insert the data into your database inside the loop, instead of echoing it out:
$errorsArray = Array (
[OBSOLETE_ORDER] => Array (
[obelisk] => 1
)
[WRONG_PERFORMANCE] => Array (
[g3t1] => 2
[g4t1] => 2
[g4t2] => 2
)
[DAY_LIMIT_EXCEEDED] => Array (
[obelisk] => 2
)
)
foreach($errorsArray as $row => $errors) {
foreach($errors as $error => $count) {
echo $row; // 'OBSOLETE_ORDER'
echo $error; // 'obelisk'
echo $count; // 1
// insert into database here
}
}
OLD ANSWER
You just need a new array to hold the information you need, ideally a count.
Im assuming that the correct data format is:
$report = [
['157479877294','OBSOLETE_ORDER','obelisk','19/01/2013 01:42pm'],
['191532426695','WRONG_PERFORMANCE','g3t1','19/01/2013 01:56pm'],
['159523681637','WRONG_PERFORMANCE','g3t1','19/01/2013 01:57pm'],
['176481653889','WRONG_PERFORMANCE','g4t1','19/01/2013 01:57pm'],
.....
];
foreach($report as $array) {
$errorName = $array[1];
$scannerName = $array[2];
if(exists($errorsArray[$errorName][$scannerName])) {
$errorsArray[$errorName][$scannerName] = $errorsArray[$errorName][$scannerName] + 1;
}
else {
$errorsArray[$errorName][$scannerName] = 1;
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return index of highest value in an array
How can i return all the index of the max value.. for example a have this array that contains grades of students
$grade = array(
"anna" => "5",
"lala"=>"7",
"eni"=>"7",
i want to return the names of the student who have the max grade
in this case should print: lala
eni
You can use max() in order to find the higest value and then do array_keys() over it.
http://php.net/manual/en/function.max.php
http://php.net/manual/en/function.array-keys.php
E.g.
$grade = array(
"anna" => "5",
"lala"=>"7",
"eni"=>"7",
$max = max($grade); // $max == 7
array_keys($grade, $max);
it looks like a school exercise ...
Ok, you can write something like that:
$maxInd = -1;
foreach($grade as $name => $ind) {
if($ind > $maxInd) {
$maxInd = $ind;
$maxRes = array();
}
if($ind == $maxInd) {
$maxRes[] = $name;
}
}
return "The highest names are " . implode(', ',$maxRes);
please, let me know if it works!
you can do sth. like this:
$inversed = Array();
$highGrade = 0;
foreach ($grade AS $student=>$grade){
if (isset($inversed[$grade]))
$inversed[$grade][] = $student;
else
$inversed[$grade] = Array($student);
if ($grade > $highGrade) $highGrade = $grade;
}
print_r($inversed[$highGrade]);
<?php
$grade = array(
"atest" => 6,
"banna" => "5",
"lala"=>"7",
"eni"=>"7");
asort($grade);
$reverse = array_reverse($grade);
$prev_val='';
$counter = 0;
foreach($reverse as $key=>$value)
{
if((($counter==1)&&($value==$prev_val))||($counter==0))
{
echo $key."->".$value."<br/>";
$prev_val = $value;
$counter++;
}
}
?>
I have added one more element to the array to clear your doubt.
I need to get one time occurence on my array, with my code I get only first result here is my example code:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
if($arrs[$arr[$i]]==1)
{
//do something...in this example i expect to receive b c and d
}
}
Thanks in advance
ciao h
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
if($arrs[$arr[$i]]==1)
{
echo $arr[$i];
}
}
That should display bcd
$arr=array("a","a","b","c","d");
$result = array();
$doubles = array();
while( !empty( $arr ) ) {
$value = array_pop( $arr );
if( !in_array( $value, $arr )
&& !in_array( $value, $doubles ) ) {
$result[] = $value;
}
else {
$doubles[] = $value;
}
}
May be you've miss your real results:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
/*
now $arrs is:
array (
'a' => 2,
'b' => 1,
'c' => 1,
'd' => 1,
)
*/
foreach($arrs as $id => $count){
if($count==1) {
// do your code
}
}
/*******************************************************/
/* usefull version */
/*******************************************************/
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
foreach($arr as $id ){
if($arrs[$id]==1){
// do your code
echo "$id is single\n";
}
}
You just need to retrieve any value which only occurs once in the array, right? Try this:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
foreach ($arrs as $uniqueValue => $count)
{
if($value == 1) {
echo $uniqueValue;
}
}
array_count_values returns an associative array where the key is the value found and its value is the number of times it occurs in the original array. This loop simply iterates over each unique value found in your array (i.e. the keys from array_count_values) and checks if it was only found once (i.e. that key has a value of 1). If it does, it echos out the value. Of course, you probably want to do something a bit more complex with the value, but this works as a placeholder.
$count = 0;
foreach(array("a","a","b","c","d") as $v){
if($v == 1){$count++;}
}