How to judge last key in multi dimentional array? - php

There are tons of mutli dimensional array.
I want to judge last key in multi dimensional array grouping by one of the value.
SO,...
TO DO: the area #Q shown below.
$i=0;
$j=0;
$limit=10;
$huge_arr = array(
array("point" => 20
"os" => "iOS"),
array("point" => 5
"os" => "iOS"),
array("point" => 10
"os" => "Android"),
array("point" => 20
"os" => "Android"),
array("point" => 7
"os" => "iOS"),
array("point" => 3
"os" => "Android"),
/*... tons of array..*/
);
foreach($huge_arr as $k => $v)
{
if($v['os'] === "iOS")
{
$i++;
if($i % $limit ===0 )
{
//Do something By $limit count :#1
}
//TO DO
//#Q:WANT TO DO same thing when there aren't $v['os'] === "iOS" in rest of $array
}
else if($v['os'] === "iOS")
{
$j++;
if($j % $limit ===0 )
{
//Do something By $limit count :#2
}
//TO DO
//#Q:WANT TO Do same thing when there aren't $v['os'] === "Android" in rest of $array
}
}
Sorting $huge_arr as new array using foreach() statement is increasing php memory.
So I do not want to do that.
this way is N.G.
foreach($huge_arr as $k => $v)
{
if($v['os'] === "iOS")
{
$ios[] = $v["point"];
}else if($v['os'] === "Android")
{
$ad[] = $v["point"];
}
}
$ios_count = count($ios);
$ad_count = count($ad);
foreach($ios as $k => $v)
{
if($k === $ios_count -1)
//do something for last value
}
foreach($ad as $k => $v)
{
if($k === $ad_count -1)
//do something for last value
}
Does anyone know smart way....

This does not require createing new arrays but rather just takes what you need from the array - assuming you will only need the last IOS and android key.
$ios_key = $ad_key = NULL; // If one of them is not present key will be NULL
// Reverse the array to put the last key at the top
array_reverse($huge_arr);
foreach($huge_arr as $k => $v)
{
// Fill key with ios key value if not already set
if($v['os'] === "iOS" AND $ios_key === NULL)
{
$ios_key = $k;
}
// Fill key with first android key value if not already set
else if($v['os'] === "Android" AND $ad_key === NULL)
{
$ad_key = $k;
}
// Stop looping when we found both keys
if($ios_key !== NULL AND $ad_key !== NULL)
break;
}
// Put the array back in original order
array_reverse($huge_array);
// Do whatever you want with the array now
For the other part of your question do the same thing when there aren't IOS ....
if($i % $limit ===0 )
into
if($i % $limit === 0 OR $k === $ios_key) // $ios_key should be the last key

Related

PHP validate array with sub array?

I have a PHP array with weekdays, by form submit I get additional data, but I want to validate this array, so if the array is empty a want to show a message, my problem there is always a sub-array called "games" and so is the main array never empty. How can I ignore them?
The "empty" array structure is like:
'monday' = ['games' = [1, 2, 3, 'game_off']],
Iterate the array and count the values for each day. Since there will always be one value for 'games', then look for counts < 2. If any are found, then that item only contains 'games' and your array is invalid.
$valid = true;
foreach ($array as $day => $values) {
if (count($values) < 2) {
$valid = false;
break;
}
}
This will verify that every day has something besides 'games'. If you need to verify that any day has something besides 'games', then the logic is the opposite.
$valid = false;
foreach ($array as $day => $values) {
if (count($values) > 1) {
$valid = true;
break;
}
}
You can walk into array and count them:
$count = 0;
foreach ($array as $item) {
if (is_array($item) && count(item) > 0){
foreach ($item as $key => $subitem) {
if ($key != 'games'){
$count++;
}
}
}
}
if ($count > 0){
//your array is valid
}

Find ARRAY by to its values

I have a multi-dimensional array like so:
$a = array(
'potatoe'=> array(
'weight'=>24,
'label'=>'kon',
'year'=>2001,
),
'apple'=> array(
'weight'=>55,
'label'=>'krakat',
'year'=>1992,
)
);
I am looking for a way to searching the fruit name (with its values) when I only know weight is 55 and year is 1992. How to do that?
Something like this perhaps
foreach ($a as $key => $value) {
if ($value['weight'] == 55 && $value['year'] == 1992) {
echo $key;
}
}
Outputs
apple
You will have to iterate over it using foreach and test every element.
function findFruit($array,$weight, $year){
foreach($array as $key => $fruit){
if($fruit['weight'] == $weight && $fruit['year'] == $year ){
return $key;
}
}
}
then, just use the function:
$theFruit = $a[findFruit($a,55,1992)];

using array_key_exists to pair up the amount total to id

I have an array that has several amounts (based on $$$ sales) attached to an id (where some of the ids are the same based on whom made a sale). My goal is to gather a total of amounts and attach each total to whichever id made the sale (truncating the identical ids from the array). I'm honestly not sure how to go about this as I'm still learning.
while ($row) {
$operearnedArray[] = array(
'amount' => $row['ChargeAmount'],
'id' => $row['OperatorID']);
}
//$operearnedArray returns the array with each "amount" attached to "id"
foreach ($operearnedArray as $key => $value) {
if($value['id'] == '' || $value['id'] == null) {
continue;
}
if(array_key_exists($value['id'], $operSums)) {
$operSums[$value['id']] += $value['amount'];
} else {
//I'm not sure where to go from here...
}
}
Your code looks fine to me, as for the comment, a simple
$operSums[$value['id']] = $value['amount'];
should do the trick. Of course it is adviseable to check for existent keys, but
foreach ($operearnedArray as $key => $value) {
if($value['id'] == '' || $value['id'] == null) {
continue;
}
$operSums[$value['id']] += $value['amount'];
}
should work just as well, as you can see in this demo.
try:
while ($row) {
$operearnedArray[] = array(
'amount' => $row['ChargeAmount'],
'id' => $row['OperatorID']);
}
$operSums = array();
foreach ( $operearnedArray as $sale ) {
if ( ! $sale['id'] ) {
continue;
}
$operSums[$sale['id']] += $sale['amount'];
}
// do something with the result, let's just look at it:
var_dump( $operSums );
It works: http://codepad.org/xGMNQauW

Compare values from 2 array PHP

I need to compare 2 values from 2 array.
I figured it out but the problem is that i need to do a comparasion between qty based on a unique id.
array 1 is from a csv:
prod_id,qty
1,1
2,3
3,1
4,3
5,1
array 2 is from database:
id,prod_id,qty
1,1,5
2,2,3
3,4,1
4,4,1
5,5,1
so now i have to compare this 2 arrays and get the difference between quantity,
for example:
id 1 has in database 5 qty and in csv 1 so it result +4
id 3 has no value in database and in csv has 1 so it result -1
i have tried with:
foreach($array1 as $csv) {
$id[] = $csv['id'];
$data[$csv['id']] = $csv['qty'];
}
foreach($array2 as $db) {
$data[$db['id']] = $db['totalQty'];
}
but it give me the result from database and result from csv.
Is there another way to compare the quantity and get only the differences ?
any help is appreciated.
If i got this correctly...
<?php
$csv = array(
0 => array('prod_id'=>1,'qty'=>1),
1 => array('prod_id'=>2,'qty'=>3),
2 => array('prod_id'=>3,'qty'=>1),
3 => array('prod_id'=>4,'qty'=>3),
4 => array('prod_id'=>5,'qty'=>1)
);
$data = array(
0 => array('id'=>1,'prod_id'=>1,'qty'=>5),
1 => array('id'=>2,'prod_id'=>2,'qty'=>3),
2 => array('id'=>3,'prod_id'=>4,'qty'=>1),
3 => array('id'=>4,'prod_id'=>4,'qty'=>1),
4 => array('id'=>5,'prod_id'=>5,'qty'=>1),
5 => array('id'=>6,'prod_id'=>6,'qty'=>7)
);
$result = array();
foreach ($data as $a=>$b) {
$data_id = $b['id'];
$data_prod_id = $b['prod_id'];
$data_qty = $b['qty'];
$in_csv = false;
foreach ($csv as $k=>$v) {
$csv_prod_id = $v['prod_id'];
$csv_qty = $v['qty'];
if ($data_prod_id == $csv_prod_id && $data_id == $csv_prod_id) {
$result[$data_id] = $data_qty - $csv_qty;
}
if ($data_id != $data_prod_id) {
$result[$data_id] = 0 - $csv_qty;
break;
}
if ($data_prod_id == $csv_prod_id) {
$in_csv = true;
}
if (!$in_csv) {
$result[$data_id] = $data_qty;
}
}
}
foreach ($result as $k=>$v) {
if ($v != 0) {
echo "ID $k has changed : $v <br>";
}
}

extract duplicates and how many times they occur in php array

I am developing a user driven eCommerce website and need some help. What I have is a function that will loop through an array remove duplicates and how many times they occur. I then need to run a function on each of those extracted duplicates as many times as they occur. The code I have so far works, but breaks when there are multiple duplicates with the same repetition count. Here is the code I have made so far..
$affiliates = array(11,11,12,12,13,13,13,14,14,14,14); //breaks the code
$affiliates = array(11,11,13,13,13,14,14,14,14,12,12,12,12,12); // works fine
$array = array();
$match_count = array();
foreach($affiliates as $key => $affiliate) {
$array[] = $affiliate;
}
arsort($array); // keeps array index in order
foreach($array as $arrays) {
if(array_value_count($arrays,$array) > 1) {
$match_count[] = array_value_count($arrays,$array);
}
}
$match_count = array_unique($match_count);
$array_unique = arrayDuplicate($array);
$final_array = array_combine($match_count,$array_unique);
foreach($final_array as $key => $value) {
for($i = 0; $i < $key; $i++) {
echo 'addOrder(affiliate_id = ' . $value . ') . '<br>';
}
}
the functions
function unique_array($array) {
return array_unique($array, SORT_NUMERIC);
}
function arrayDuplicate($array) {
return array_unique(array_diff_assoc($array,array_unique($array)));
}
function array_value_count($match, $array) {
$count = 0;
foreach ($array as $key => $value)
{
if ($value == $match)
{
$count++;
}
}
return $count;
}
to fix the duplicates breaking the code I have tried this
if(count($array_unique) - count($match_count_unique) == 1 ) // do something
or
if(count($array_unique) != count($match_count_unique) == 1 ) // do something
How would I know where to add the missing duplicate value count and array items correctly without them getting out of sync? OR Is there a better way of doing this?
Taken from How do I count occurrence of duplicate items in array
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);
Result
No. of NON Duplicate Items: 7
Array
(
[12] => 1
[43] => 6
[66] => 1
[21] => 2
[56] => 1
[78] => 2
[100] => 1
)
Duplicate items = (Array Size) - (Total Number of Unique Values)
<?php
$affiliates = array(11,11,12,12,13,13,13,14,14,14,14);
// get an array whose keys are the aff# and
//the values are how many times they occur
$dupes = array();
foreach ($affiliates as $aff) {
$dupes[$aff]++;
}
// remove the 1's since those aren't dupes
$dupes = preg_grep('~^1$~',$dupes,PREG_GREP_INVERT);
// de-dupe the original array
$affiliates = array_unique($affiliates);
// for each duped affiliate...
foreach ($dupes as $aff => $affCount) {
// for each time it was duped..
for ($c=0;$c<$affCount;$c++) {
// do something. $aff is the aff# like 11
}
}
?>

Categories