using array_key_exists to pair up the amount total to id - php

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

Related

Compare multidimensional array values by key in php

I have an array of the products as in the sample below. Products can be two, or three and more. In this example, three.
$all_products = array(
'product_1' =>array(
'price' =>'$100',
'quantity' =>'2pcs.',
'availability'=>'In Stock',
'manufacturer'=>'Apple'),
'product_2' =>array(
'price' =>'$200',
'quantity' =>'2pcs.',
'availability'=>'In Stock',
'manufacturer'=>''),
'product_3' =>array(
'price' =>'$300',
'quantity' =>'2pcs.',
'availability'=>'In Stock',
'manufacturer'=>'')
);
I need to compare values of the products by each key. To highlight rows in the compare table where price, quantity, availability, or manufacturer is different.
I have tried this function to check which values are different and return one temp array:
function compare_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (isset($val[$key])) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
}
$i++;
}
return $temp_array;
}
and then:
foreach ($all_products as $products) {
foreach ($products as $product_key => $val) {
foreach ($this->compare_array($all_products, $product_key) as $temp_value) {
if ($val != $temp_value) {
$style[$product_key] = 'style="background-color: lightblue;"';//style for highlight
}
}
}
}
Problem is when some value in array is empty. Like in this example, manufacturer.
Maybe someone has more light solution?
I need compare values of the products by each key. To highlight rows
in the compare table where price, quantity, availability, or
manufacturer is different.
If you want to highlight all products unless all of them have exactly the same price, quantity, availability, or manufacturer.
function:
function productsIdentical(array &$products) : bool
{
if (count($products) < 2) {
throw new \InvalidArgumentException("You should pass at least 2 products to compare");
}
$compare = '';
foreach ($products as $product) {
ksort($product); //to make comparison of key order insensitive
$sha = sha1(json_encode($product));
if (empty($compare)) {
$compare = $sha;
} elseif ($sha !== $compare) {
return false;
}
}
return true;
}
returns true only if all products' fields have exactly the same keys and value, otherwise it returns false
so you use it this way:
$identicalFlag = productsIdentical($all_products);
if ($identicalFlag === false) {
echo "Products are not identical:" . PHP_EOL;
$nonIdenticalProductsArr = array_keys($all_products);
echo "Non identical products are:" . PHP_EOL;
print_r($nonIdenticalProductsArr);
//do your styling on $nonIdenticalProducts
} else {
echo "Products are identical" . PHP_EOL;
}
Output:
for identical products:
Products are identical
for non identical:
Products are not identical:
Non identical products are:
Array
(
[0] => product_1
[1] => product_2
[2] => product_3
)
Or if you want to detect every product field that is not the same across all products in the array use this function:
function getFieldsNonIdentical(array &$products) : array
{
if (count($products) < 2) {
throw new \InvalidArgumentException("You should pass at least 2 products to compare");
}
$compareArr = [];
$keyDifferentArr = [];
foreach ($products as $product) {
foreach($product as $key => $val) {
if (!key_exists($key, $compareArr)) {
$compareArr[$key] = $val;
} elseif ($compareArr[$key] !== $val) {
$keyDifferentArr[$key] = true;
}
}
}
return array_keys($keyDifferentArr);
}
this way:
$fieldsNonIdentical = getFieldsNonIdentical($all_products);
if (!empty($fieldsNonIdentical)) {
echo "Fields that are non identical:" . PHP_EOL;
print_r($fieldsNonIdentical);
//do your styling
$nonIdenticalStyle = 'style="background-color: lightblue;"';
$styleArr = [];
foreach ($fieldsNonIdentical as $key => $value) {
$styleArr[$value] = $nonIdenticalStyle;
}
echo "Non Identical fields styling is:" . PHP_EOL;
print_r($styleArr);
} else {
echo "All fields in all products are the same." . PHP_EOL;
}
Output
for identical:
All fields in all products are the same.
for non identical:
Fields that are non identical:
Array
(
[0] => price
[1] => manufacturer
)
Non Identical fields styling is:
Array
(
[price] => style="background-color: lightblue;"
[manufacturer] => style="background-color: lightblue;"
)

How to modifying the data structure of array list as per key value using PHP

I need to modify the data structure of json array list as per some key value using PHP. I am explaining my code below.
<?php
$output=array(
array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA001"
),array(
"first_name"=>"robin",
"last_name"=>"sahoo",
"reg_no"=>12,
"paper_code"=>"BA002"
),array(
"first_name"=>"Rama",
"last_name"=>"Nayidu",
"reg_no"=>13,
"paper_code"=>"BA001"
)
);
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$result[]=array(
"name"=>$value["first_name"].' '.$value['last_name'],
"reg_no"=>$value['reg_no'],
"paper1"=>$value['paper_code'],
"paper2"=>"",
"paper3"=>"",
"paper4"=>""
);
}
}
The output of the input array is given below.
// Output:
[
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA001"
},
{
"first_name":"robin",
"last_name":"sahoo",
"reg_no":12,
"paper_code":"BA002"
},
{
"first_name":"Rama",
"last_name":"Nayidu",
"reg_no":13,
"paper_code":"BA001"
}
];
The above is my array list. Here I need to modify the all row value by reg_no means if there are multiple rows including same reg_no then those will merge with joining the both name and my expected output should like below.
expected output:
[
{
'name':"robin sahoo",
"reg_no":12,
"paper1":"BA001",
"paper2":"BA002",
"paper3":"",
"paper4":""
},
{
'name':"Rama Nayidu",
"reg_no":13,
"paper1":"BA001",
"paper2":"",
"paper3":"",
"paper4":""
}
]
Here paper1,paper2,paper3,paper4 will be selected serially means suppose same reg_no=12 has first row paper_code= BA001 then it will be paper1=BA001 and second row paper_code=BA002 then it will be paper2=BA002 and so on. Here I am using PHP to map this array.
Try the following, Let me know..
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
$temp=array();
if(!empty($output)){
foreach ($output as $key => $value) {
if(isset($temp[$value['reg_no']])){
if(empty($temp[$value['reg_no']]["paper1"]) || $temp[$value['reg_no']]["paper1"] == ""){
$temp[$value['reg_no']]["paper1"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper2"]) || $temp[$value['reg_no']]["paper2"] == ""){
$temp[$value['reg_no']]["paper2"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper3"]) || $temp[$value['reg_no']]["paper3"] == ""){
$temp[$value['reg_no']]["paper3"] = $value['paper_code'];
}else if(empty($temp[$value['reg_no']]["paper4"]) || $temp[$value['reg_no']]["paper4"] == ""){
$temp[$value['reg_no']]["paper4"] = $value['paper_code'];
}
}else{
$temp[$value['reg_no']] = array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}
}
if(!empty($temp)){
foreach ($temp as $key => $value) {
$result[] = $value;
}
}
This Code May help you
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001"));
//echo json_encode($output);
$result=array();
foreach ($output as $key => $value) {
if (count($result)==0) {
$output[$key]=array("name"=>$value["first_name"].' '.$value['last_name'],"reg_no"=>$value['reg_no'],"paper1"=>$value['paper_code'],"paper2"=>"","paper3"=>"","paper4"=>"");
}
}echo "<pre>";print_r($output);
?>
You can try with this
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'name' => $name,
'reg_no' => $value['reg_no'],
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'];
}
$result = array_values($result); // reindex result array
$result = json_encode($result); // Encode to json format
print_r($result); // print result
This assumes that first_name and last_name is always same for each reg_no

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)];

How to judge last key in multi dimentional array?

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

How to compare textbox value if exist in 2d array?

I have this code and I need to compare the user input and the hardcoded 2d array. Can somebody help me with this? Thanks!
if (isset($_POST['submit']))
{
$array = array
(
0=>array
( 'username'=>'Art',
'password'=>'p#ssw0rd',
'user_id'=>'1'
),
1=>array
( 'username'=>'Berto',
'password'=>'1234',
'user_id'=>'2'
),
2=>array
( 'username'=>'Carrie',
'password'=>'5678',
'user_id'=>'3'
),
3=>array
( 'username'=>'Dino',
'password'=>'qwer',
'user_id'=>'4'
),
4=>array
( 'username'=>'Ely',
'password'=>'asdf',
'user_id'=>'5'
)
);
if(in_array($_POST['user'], $users))
{
$key = array_search($_POST['user'], $users);
I want to match the username if it exist through the 2d array. It is also the same for the password field.
You can do this through foreach loop
foreach($array as $key=>$value)
{
if($value['username'] == $_POST['user'] && $value['password'] == $_POST['pwd'])
{
// do whatever you want to do here
}
}
function searchForValue($fkey, $uvalue, $array) {
foreach ($array as $key => $val) {
if ($val[$fkey] == $uvalue) {
return $key;
}
}
return null;
}
call it like this
$id = searchForValue('username', $_POST['user'], $<yourarray>);
in case of password search
$id = searchForValue('password', $_POST['pass'], $<yourarray>);
You've defined your array name as $array but using $users in the in_array().
Anyways, suppose you use the correct name, you can match like this:
foreach ($users as $key => $item)
{
if ($item['username'] === $_POST['user'] &&
$item['password'] === $_POST['password'])
return $key;
return false;
}

Categories