PHP two dimensional array array search - php

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;
}

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";
}
}

Search value in multidimensional array and sum the value

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."
}

Compare two arrays and merging in PHP

I have two arrays:
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
Here $array1 has keys and values. Now I want to take the first value from $array1(as 1) and I want to check if this is repeated in this array .
Here 1 is repeated two times so I want to take the two keys 1,10 and display the corresponding values of these keys from $array2. If the value in $array1 is not repeated then I want to just display the value of this key from $array2.
I want to get the output as follows:
Hello Test
check
error
That means in $array1 1,10 keys have the same value so the value of 1 and the value of 10 from $array2 is merged then displayed.
Like 12 has 0 this is not repeated so simply take value of 12 from $array2.
Like 13.
How can I do this?
<?php
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$groupedKeys = array();
foreach($array1 as $key=>$arr){
$groupedKeys[$arr][] = $key;
}
foreach($groupedKeys as $key => $groupedKeyArr){
foreach($groupedKeyArr as $groupedKey){
echo $array2[$groupedKey];
}
echo "<br /> ";
}
?>
http://codepad.org/9R9s5lTM
There is a built in function that returns an array with the number of times a value is repeated http://php.net/manual/en/function.array-count-values.php
This is really rough, but a simple way of doing it could be:
<?
$array1 = array(1=>1,10=>1,12=>0,13=>13);
$array2 = array(1=>"Hello",10=>"Test",12=>"check",13=>"error");
$prev = $array1[1];
foreach($array1 as $key => $val)
{
if($val != $prev && $key != 1)
{
echo '<br />';
}
echo $array2[$key].' ';
$prev = $val;
}
?>
Example: http://codepad.org/OpLdtStp
This assumes that you're first key is always going to be 1 by the way.
I am providing you a function returns an array with the number of times a value is repeated in an array(as values) and values as the keys. Further task is not difficult.
function check_number_of_times_elements_occur_in_array($a)//returns values of array as keys, associating values being their total occurences in the array
{
$r=array();
foreach($a as $v)
++$r[$v];
return $r;
}
I think this will do for you..
function test($array1,$array2) {
$repeated_values = array_count_values($array1);
foreach($repeated_values as $key => $value){
if($value > 1) {
foreach($array1 as $key1 => $value1){
if($key == $value1){
$repeated_values_keys[] = $key1;
}
}
}
}
$str_top = "";
foreach($repeated_values_keys as $k){
$str_top .= $array2[$k]." ";
}
echo $str_top.'<br/>';
foreach($array2 as $key2 => $value){
if(!in_array($key2,$repeated_values_keys)){
echo $value.'<br/>';
}
}
}

Unset array element inside a foreach loop

So here is my code:
<?php
$arr = array(array(2 => 5),
array(3 => 4),
array(7 => 10));
foreach ($arr as $v) {
$k = key($v);
if ($k > 5) {
// unset this element from $arr array
}
}
print_r($arr);
// now I would like to get the array without array(7 => 10) member
As you can see, I start with an array of single key => value arrays, I loop through this array and get a key of the current element (which is a single item array).
I need to unset elements of the array with key higher than 5, how could I do that? I might also need to remove elements with value less than 50 or any other condition. Basically I need to be able to get a key of the current array item which is itself an array with a single item.
foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}
It is safe in PHP to remove elements from an array while iterating over it using foreach loop:
foreach ($arr as $key => $value) {
if (key($value) > 5) {
unset($arr[$key]);
}
}
Use key() to get the first key from the sub-array.
foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}
It's not really safe to add or delete from a collection while iterating through it. How about adding the elements you want to a second array, then dumping the original?
To unset array element we Used unset() and php function like below:
foreach($array as $key=>$value)
{
if(key($value) > 5)
{
unset($array[$key]);
}
}

php - how do I display items from an array with their values

I have this array:
Array ( [#LFC] => 1 [#cafc] => 2 [#SkySports] => 1)
How do i display it like this on a page? (preferably in value descending order as below):
\#cafc (2), #LFC (1), #SkySports (1)
Thanks
First, sort the array
arsort($arrayName);
Next, iterate througth the array keys and values.
foreach($arrayName as $key => $value)
{
echo "$key ($value),";
}
Try using arsort to sort by descending value and then looping through the array, printing key/value pairs, as follows:
arsort($original_array);
foreach($original_array as $k => $v) {
echo $k.'('.$v.')';
}
if i got your question right, use a foreach loop in combination with arsort:
arsort($array);
foreach($array as $k => $v) {
printf('%s (%s)',
htmlspecialchars($k),
htmlspecialchars($v));
}
arsort($array);
$output = array();
foreach($array as $k => $v) {
$output[] = "$k ($v)";
}
print implode(", ", $output);
this will sort the array in reverse order, then create a new array with the data formatted the way you like, then implodes the output into a string separated by commas. The other answers so far will leave a dangling comma.

Categories