How can I count in a multidimensional array the number of element with a special condition ?
Array
(
[0] => Array
(
[item] => 'Banana'
)
[1] => Array
(
[item] => 'Banana'
)
[2] => Array
(
[item] => 'Cherry'
)
[3] => Array
(
[item] => 'Apple'
)
)
For example, for this array I should find 2 for Banana.
Si I tried:
$i=0;
foreach($array as $arr) {
if($arr[item]=='Banana') { $i++; }
}
Is there a better solution please ?
Thanks.
Method 1:
Using built-in functions - array_column and array_count_values:
print_r(array_count_values(array_column($arr,'item')));
Method 2:
Using foreach with simple logic of making your fruit as key and its count as value:
$arr = [
["item"=>"Banana"],
["item"=>"Banana"],
["item"=>"Cherry"],
["item"=>"Apple"]
];
$countArr = [];
foreach ($arr as $value) {
$item = $value['item'];
if(array_key_exists($item, $countArr)) // If key exists, increment its value
$countArr[$item]++;
else // Otherwise, assign new key
$countArr[$item] = 1;
}
print_r($countArr);
Final result in both case would be:
Array
(
[Banana] => 2
[Cherry] => 1
[Apple] => 1
)
So when you want Banana's count, you can get it like this:
echo $countArr['Banana'];
Use array_count_values(), it is pretty straight forward:
foreach($array as $arr) {
$new[] = $arr['item'];
}
print_r(array_count_values($new));
On a side note, there isn't anything wrong with your approach, unless you want to count all values. Also on a side note, I think you'll find a foreach() will eek out a slightly faster time than array_column(), especially on a large array.
Related
This has to be easy but I am struggling with it. If the array below exists (named "$startersnames") and I specifically want to echo the value that has "qb" as the key, how do I do that?
I assumed $startersnames['qb'], but no luck.
$startersnames[0]['qb'] works, but I won't know that it's index 0.
Array
(
[0] => Array
(
[qb] => Tannehill
)
[1] => Array
(
[rb] => Ingram
)
[2] => Array
(
[wr] => Evans
)
[3] => Array
(
[wr] => Hopkins
)
[4] => Array
(
[wr] => Watkins
)
[5] => Array
(
[te] => Graham
)
[6] => Array
(
[pk] => Hauschka
)
[7] => Array
(
[def] => Rams
)
[8] => Array
(
[flex] => Smith
)
)
You can use array_column (from php 5.5) like this:
$qb = array_column($startersnames, 'qb');
echo $qb[0];
Demo: http://3v4l.org/QqRuK
This approach is particularly useful when you need to print all the wr names, which are more than one. You can simply iterate like this:
foreach(array_column($startersnames, 'wr') as $wr) {
echo $wr, "\n";
}
You seem to be expecting an array with text keys and value for each, but the array you have shown is an array of arrays: i.e. each numeric key has a value which is an array - the key/value pair where you are looking for the key 'qb'.
If you want to find a value at $array['qb'] then your array would look more like:
$array = [
'qb' => 'Tannehill',
'rb' => 'etc'
];
now $array['qb'] has a value.
If the array you are inspecting is a list of key/value pairs, then you have to iterate over the array members and examine each (i.e. the foreach loop shown in your first answer).
For your multi-dim array, you can loop through the outer array and test the inner array for your key.
function findKey(&$arr, $key) {
foreach($arr as $innerArr){
if(isset($innerArr[$key])) {
return $innerArr[$key];
}
}
return ""; // Not found
}
echo findKey($startersnames, "qb");
You can try foreach loop
$key = "qb";
foreach($startersnames as $innerArr){
if(isset($innerArr[$key])) {
echo $innerArr[$key];
}
}
$keyNeeded = 'qb';
$indexNeeded = null;
$valueNeeded = null;
foreach($startersnames as $index => $innerArr){
//Compare key
if(key($innerArray) === $keyNeeded){
//Get value
$valueNeeded = $innerArr[key($innerArray)];
//Store index found
$indexNeeded = $index;
//Ok, I'm found, let's go!
break;
}
}
if(!empty($indexNeeded) && !empty($valueNeeded)){
echo 'This is your value: ';
echo $startersnames[$indexNeeded]['qb'];
echo 'Or: ':
echo $valueNeeded;
}
http://php.net/manual/en/function.key.php
Assuming that I have an array of objects like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 26-295-1006
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 12-330-1000
[qty] => 2
[price] => 230.35
)
And I have another array of object hat looks like this:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I want to loop through the 2nd array of objects and get the 'itemVendorCode' and then use it as the 'id' to get the object from the first array of objects. Is there a way to obtain what I want without looping the first array? Looping is very costly in my use-case.
You will have to use loops in any case, even if those loops are hidden within PHP built-in functions.
For instance:
$codes = array_map(function ($item) { return $item->itemVendorCode; }, $array2);
$items = array_filter($array1, function ($item) use ($codes) { return in_array($item->id, $codes); });
// $items contains only elements from $array1 that match on $array2
If this will be more efficient than using regular loops is hard to tell.
Since you are aparently trying to code what is supposed to be a DBMS's job, I recommend you export those tables to a database server such as MySQL instead and let it work its magic on those "JOINs".
Answering your comment, you could merge with something like this:
$result = array();
foreach ($array1 as $item1)
foreach ($array2 as $item2)
if ($item1->id == $item2->itemVendorCode)
$result[] = (object)array_merge((array)$item1, (array)$item2));
$result will contain a new set of objects that merge properties from both $array1 and $array2 where they intersect in id == itemVendorCode.
Do you need first arrays index keys? if not you could iterate throuh first array once and set key to id. Something like:
foreach ($items as $key => $item) {
$items[$item->id] = $item;
unset($items[$key]);
}
Here is another direct approach to solve this problem, even better than the one I proposed earlier:
// you got the $itemVendorCode from looping through the second array, let say :
$itemVendorCode = "89-605-1250";
// I'm assuming that you converted the array of objects in into accessible multidimensional array
// so the $first_array would look like :
$first_array= array (
array (
"id" => "10-423-1176",
"qty" => 2,
"price" => 12.6
),
array (
"id" => "10-423-1176",
"qty" => 5,
"price" => 25
),
array (
"id" => "89-605-1250",
"qty" => 12,
"price" => 30
)
);
// Now you can filter the first array using
$filter = function ($player) use($itemVendorCode) {
return $player ['id'] == $itemVendorCode;
};
$filtered = array_filter ( $first_array, $filter );
// print the price of the matching filtered item
print $filtered[key($filtered)]['price'] ;
You can use the array_map and array_filter() function to achieve that.
Try with this code:
<?php
$first = array();
$first[0] = new stdClass;
$first[0]->id = '89-605-1250';
$first[0]->qty = 2;
$first[0]->price = 12.6;
$first[1] = new stdClass;
$first[1]->id = '89-575-2354';
$first[1]->qty = 24;
$first[1]->price = 230.35;
$last = array();
$last[0] = new stdClass;
$last[0]->internalId = 14062;
$last[0]->itemVendorCode = '89-605-1250';
$last[1] = new stdClass;
$last[1]->internalId = 33806;
$last[1]->itemVendorCode = '89-575-2354';
$ids = array_map(function($element){return $element->itemVendorCode;}, $last);
$to_find = $ids[0];
$object = array_filter($first, function($element){global $to_find; return $element->id == $to_find ? true: false;})[0];
print_r($object);
?>
Output:
stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 12.6
)
try using array_search:
http://php.net/manual/en/function.array-search.php
foreach($array2 as $key=>$item) {
$firstArrayObjectKey = array_search($item['itemVendorCode'], $array1);
//... do something with the key $firstArrayObjectKey
}
In this case you'll need to loop through the first array to get the itemVendorCode.
Right after that you can use the itemValue you got from the previous process to search in a reduced array of the first object using array_reduce function:
http://php.net/manual/en/function.array-reduce.php
In php, i am new in php anybody help me for this?
i have two arrays , in Array2 i have two records, i want to check Data of Array2 whether in Array1 or not , how can i check the data of Array2 in Array1 its available or not !
Thanks in advance
Array1
[items] => Array
(
[0] => Array
(
[abc] => z1
[xyz] => cool
[val] => 2.32
[color] => D
)
[1] // i have 5o records in array1
);
Array 2
[items] => SearchArray
(
[0] => Array
(
[abc] => z1
[xyz] => cool
[val] => 2.32
[color] => D
)
[1] // i have 2 records
);
Please try this code - I hope it helpes some way :
$matches = array();
for($i2 = 0; $i2 < count($Array2); $i2++)
{
for($i1 = 0; $i1 < count($Array1); $i1++)
{
$bMatch = TRUE;
foreach($Array1[$i1] as $key => $val)
{
if($Array2[$i2][$key] !== $val)
{
$bMatch = FALSE;
break;
}
}
if($bMatch)
{
$matches[] = array($i2, $i1);
}
}
}
It iterates through both arrays, comparing elements (which in fact are sub arrays) in such way that they are equal only if all elements of sub array from $Array2 are equal to all elements of sub array from $Array1. If the match is found, the pair ($i2, $i1) is added to the $matches array, so in the end, basing on your example, you would have something like:
$matches => array (
[0] => array (0, 0)
...
)
I hope the assumption made is the proper one.
Can use array_search method. For more information, check out the manual reference: http://php.net/manual/en/function.array-search.php
Well this has been a headache.
I have two arrays;
$array_1 = Array
(
[0] => Array
(
[id] => 1
[name] => 'john'
[age] => 30
)
[1] => Array
(
[id] => 2
[name] => 'Amma'
[age] => 28
)
[2] => Array
(
[id] => 3
[name] => 'Francis'
[age] => 29
)
)
And another array
array_2 = = Array
(
[0] => Array
(
[id] => 2
[name] => 'Amma'
)
)
How can I tell that the id and name of $array_2 are the same as the id and name of $array_1[1] and return $array_1[1]['age']?
Thanks
foreach($array_1 as $id=>$arr)
{
if($arr["id"]==$array_2[0]["id"] AND $arr["name"]==$array_2[0]["name"])
{
//Do your stuff here
}
}
Well you can do it in a straightforward loop. I am going to write a function that takes the FIRST element in $array_2 that matches something in $array_1 and returns the 'age':
function getField($array_1, $array_2, $field)
{
foreach ($array_2 as $a2) {
foreach ($array_1 as $a1) {
$match = true;
foreach ($a2 as $k => $v) {
if (!isset($a1[$k]) || $a1[$k] != $a2[$k]) {
$match = false;
break;
}
}
if ($match) {
return $a1[$field];
}
}
}
return null;
}
Use array_diff().
In my opinion, using array_diff() is a more generic solution than simply comparing the specific keys.
Array_diff() returns a new array that represents all entries that exists in the first array and DO NOT exist in the second array.
Since your first array contains 3 keys and the seconds array contains 2 keys, when there's 2 matches, array_diff() will return an array containing the extra key (age).
foreach ($array_1 as $arr) {
if (count(array_diff($arr, $array_2[1])) === 1) {//meaning 2 out of 3 were a match
echo $arr['age'];//prints the age
}
}
Hope this helps!
I assume you want to find the age of somebody that has a known id and name.
This will work :
foreach ($array_1 as $val){
if($val['id']==$array_2[0]['id'] && $val['name']==$array_1[0]['name']){
$age = $val['age'];
}
}
echo $age;
Try looking into this.
http://www.w3schools.com/php/func_array_diff.asp
And
comparing two arrays in php
-Best
My question is maybe repetitive but I really find it hard. (I have read related topics)
This is the array :
Array
(
[0] => Array
(
[legend] => 38440
)
[1] => Array
(
[bestw] => 9765
)
[2] => Array
(
[fiuna] => 38779
)
[3] => Array
(
[adam] => 39011
)
[4] => Array
(
[adam] => 39011
)
[5] => Array
(
[adam] => 39011
)
)
I have tried many ways to handle this array and find out the most common value. The result I expect is "adam"
$countwin = array_count_values($winnernames);
$maxwin = max($countwin);
$mostwinner = array_keys($countswin, $maxwin);
EDIT : My array is like this array("A"=>"1" , "B"=>"2" , "A"=>"1") it should return A is the most common
How about iterating your array and counting the values you've got?
$occurences = array();
foreach ($data as $row) {
foreach ($row as $key => $score) {
if (empty($occurences[$key])) {
$occurences[$key] = 1;
} else {
$occurences[$key]++;
}
}
}
and then sorting that
arsort($occurences);
and grabbing the first element of the sorted array
$t = array_keys($occurences);
$winner = array_shift($occurences);
You may try this code. A brute force method indeed. But a quick search made me to find this an useful one:
function findDuplicates($data,$dupval) {
$nb= 0;
foreach($data as $key => $val)
if ($val==$dupval) $nb++;
return $nb;
}
EDIT : Sorry, I misinterpreted your question! But it might be the first hint of finding the one with maximum counter.