Search value in multidimensional array and sum the value - php

I'm trying to do a function that search a value inside a multidimensional array and adding up the value from the findings. The array is as below
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
I'm trying to search all 'MY106782' inside the "SponsorID" array, get the 'totalSales' value when found and add the values if the is multiple records

Since your array is a key value pair arrays, you have to determine which key are you looking for. Check this:
$sponsor_id = "MY106782";
$total_sales = 0;
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
foreach($arr as $values) {
if($values["SponsorID"] == $sponsor_id) {
$total_sales += (float)$values["totalSales"];
}
}
echo $sponsor_id . " - " . $total_sales;

try to something like this
$i = 0;
foreach ($arr as $key => $value) {
if ($value['SponsorID'] == 'MY106782') {
$i++;
}
}
Output: 2

You can use below script if key is exist only once time in a array.
$arr = array (
'MY106782'=> array ('code'=>"MY106782",'totalSales'=>"5625.00",'SponsorID'=>"MY246913"),
'MY126192'=> array ('code'=>"MY126192",'totalSales'=>"5625.00",'SponsorID'=>"MY126637"),
'MY128276'=> array ('code'=>"MY128276",'totalSales'=>"3180.00",'SponsorID'=>"MY106782"),
'MY157278'=> array ('code'=>"MY157278",'totalSales'=>"5625.00",'SponsorID'=>"MY477500"),
'MY167585'=> array ('code'=>"MY167585",'totalSales'=>"5625.00",'SponsorID'=>"MY106782")
);
$key_to_check = 'MY157278';
if (array_key_exists($key_to_check, $arr)) {
echo $arr[$key_to_check]['totalSales'];
}else{
echo "key not found."
}

Related

Compare all value of two array in one foreach

I've 2 array in php
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
This is a result of select query wrote in codeigniter. so that is associative array. This is 2 query result one is for user list and second is for invited user list. I want check in user list which user is invited. So that I want to compare that array
foreach ($array1 as $key => $value) {
if($array2[$key]->invite_user_id==$value->user_id) {
echo "Matched";
}
}
but it compare only 2 value of array1 with array2 3rd value is not compare. How it could compare all value of array1 and array2 in above foreach loop
I found that answer
$array1=array('user_id'=>'1','user_id'=>'2','user_id'=>'3');
$array2=array('invite_user_id'=>'1','invite_user_id'=>'3');
$invitationset = [];
foreach ($array2 as $invite) {
$invitationset[$invite->invite_user_id] = $invite->invite_user_id;
}
foreach ($array1 as $key => $value) {
if(isset($invitationset[$value->user_id])){
if($invitationset[$value->id]==$value->user_id){
echo "Matched";
}
}
}
In your assoc arrays you have dublicate keys. So if you use:
print_r( $array1 );
You'll see that your array only contains the last entry:
Array ( [user_id] => 3 )
I think that is not what you have expected. So you have to use different keys like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
Or you even dont use assoc arrays because it is obsolete in your example but never mind:
$user_ids = array('1','2','3');
$invited_user_ids = array('1','3');
You can compare your assoc arrays like that:
$array1 = array('user_id_1'=>'1','user_id_2'=>'2','user_id_3'=>'3');
$array2 = array('invite_user_id_1'=>'1','invite_user_id_2'=>'3');
foreach ($array1 as $user_id) {
if( in_array( $user_id, $array2 ) ) {
echo "Matched id: $user_id";
}
}

PHP two dimensional array array search

Please help me with the code to search for a particular value in a two-dimensional array and print the values returned in PHP. Thanks in advance.
in the below array i want to search for value 15 and print 12
code:
$speed = array
(
array(5,4),
array(10,8),
array(15,12),
array(20,16),
array(25,20),
array(30,24),
array(35,28),
array(40,32),
array(45,36),
array(51,40),
array(56,44)
);
foreach ($speed as $key => $val)
{
}
foreach ($speed as $key => $val)
{
if($val[0] === 15)
{
echo $val[1];
}
}
$val is an array so first index is your search and second is your value.
When you browse the array, a row is an array in your input. So if you want to check for 15 and to print 12, you have to do :
// For each row of my array $speed, I have an array that I will call $arr
foreach($speed as $arr){
if(15 == $arr[0]) {
echo $arr[1];
}
}
you can use in_array
loop through the array and search for the value in the array using in array
foreach ($speed as $key => $val)
{
echo (in_array(15, $val)) ? $val[1] :NULL;
}

How do I loop through a multidimensional array to retrieve keys where the value is one?

Here is my array: [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]]
My goal is to make an array or string (unsure of best method) called results where the value of the licenses is 1.
For example: The results should be something like: STR_Licenses_Driver, STR_Licenses_Pilot.
I am currently using PHP Version 7, and Laravel Version 5.5
JSON Decode the $this->license and do the loop.
Whole code:
$licenses = $this->licenses;//This is your posted array string
$result = json_decode($licenses);
$licenses_with_1 = array();
foreach($result as $i){
foreach($i as $key => $value){
if($value == 1){
$licenses_with_1[] = $i[0];
}
}
}
print_r($licenses_with_1);
Result:
Array ( [0] => STR_License_Driver [1] => STR_License_Pilot )
I remember Python on your data structure.
Try my solution:
https://3v4l.org/nrfqZ
$licenses = [["STR_License_Driver",1],["STR_License_Truck",0],["STR_License_Pilot",1],["STR_License_Firearm",0],["STR_License_Rifle",0]];
Map over filtered array having second item equal to 1 to get the license names.
$filterVal = 1;
$licenseNames = array_map(
function ($item) { return $item[0]; },
array_filter(
$licenses,
function ($item) use ($filterVal) { return $item[1] === $filterVal; }
)
);
Then implode array of license names to join by glue string.
echo implode($licenseNames, ', ');

PHP get first and forth value of an associative array

I have an associative array, $teams_name_points. The length of the array is unknown.
How do I access the first and forth value without knowing the key of this array in the easiest way?
The array is filled like this:
$name1 = "some_name1";
$name2 = "some_name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;
etc.
I want to do something like I do with an indexed array:
for($x=0; $x<count($teams_name_points); $x++){
echo $teams_name_points[$x];
}
How do I do this?
use array_keys?
$keys = array_keys($your_array);
echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key
You can use array_values which will give you a numerically indexed array.
$val = array_values($arr);
$first = $val[0];
$fourth = $val[3]
In addition to the array_values, to loop through as you show:
foreach($teams_name_points as $key => $value) {
echo "$key = $value";
}
You can get use the array_keys function such as
//Get all array keys in array
$keys = array_keys($teams_name_points);
//Now get the value for 4th key
//4 = (4-1) --> 3
$value = $teams_name_points[$keys[3]];
You can get all values now as exists
$cnt = count($keys);
if($cnt>0)
{
for($i=0;$i<$cnt;$i++)
{
//Get the value
$value = $team_name_points[$keys[$i]];
}
}

php array key issue with foreach loop and multi-dim arrays

I have listed an example below. What I need is for $key to return the actual index number (position) in the array during the loop, but instead it is returning Array. The same code works fine when given a single dimension array, but not in the example below.
GIVEN:
$screenshots would be similar to the following with only more entries.
Array
(
[0] => Array
(
[screenshot_id] => 871
[image_filename] => DSCF0124.JPG
)
)
PHP:
//build in clause & binding using selected array from above
$prefix = $in_clause = '';
$binding_clause = array();
foreach($screenshots as $key)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $key['screenshot_id'];
}
RESULT:
$inclause = :selected_Array
$binding_clause =
Array
(
[:selected_Array] => 871
)
EXPECTED:
$inclause = :selected_0
$binding_clause =
Array
(
[:selected_0] => 871
)
Just because you call it $key doesn't make it a key. You need the key and the value (inner array):
foreach($screenshots as $key => $value)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $value['screenshot_id'];
}
You need to tell it that you want the KEY and the VALUE.
like this:
foreach($screenshots as $key=>$screenShot)
That will get you the key and the value.
You just need to change your foreach to cast keys and values
foreach($screenshots as $key => $val)
Now the key is in your $key variable while you can access elements with $val array, for example $key['screenshot_id']
You can have a check to documentation examples here
Try:
foreach($screenshots as $key => $screenshot)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $screenshot['screenshot_id'];
}
Read more about PHP foreach: http://php.net/manual/en/control-structures.foreach.php

Categories