PHP - Get the key of a subarray based on a value within - php

I'm trying to get the key of a subarray based on a value in that subarray. So, based on the example below, how can I return the key of the array containing 'apple'?
Array (
[0] => Array (
[fruit] => apple
[colour] => green
)
[1] => Array (
[fruit] => banana
[colour] => yellow
)
)
So logically, something like:
if ('apple' is in $subarray) {
echo $subarray_key;
}
Thanks in advance.

Assuming that your array is stored in $arr variable, you can do
foreach($arr as $key => $value){
if(in_array('apple',$value){
echo $key;
}
}

foreach($array as $key => $val){
if($val == 'apple'){
print $key;
}
}
You can use array keys and do some other stuff but for the most part you're going to end up just iterating through the array anyways

Related

php combines array values in main array

I have total 3 array
First array contains list of titles
Second array contains list of description
third array contains images
I have already combine 1st and 2nd array as a key of first array and value of second array and I also combine 1st and 3rd array as key of 1st and value of 3rd.
Following is my arrays
1 )
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[0] => Array
(
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
)
I want output like
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
Code
foreach ($images as $key => $value) {
$values['image']= $value;
}
$data = array_combine($_POST['title'], $images);
$mainArray = array_combine($_POST['title'], $_POST['Description']);
array_push($mainArray,$data);
echo '<pre>';
print_r($mainArray);
How can I do this?
The code below should produce the format the array as required above, although it is not the most elegant way to flatten an array. It may be worthwhile looking at previous questions like How to Flatten a Multidimensional Array?
$newArr = array();
foreach ( $mainArray as $key => $val ) {
if ( is_array( $val ) ) {
foreach ( $val as $key2 => $val2 ) {
$newArr[$key2] = $val2;
}
} else {
$newArr[$key] = $val;
}
}

Count the item from an array in PHP

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.

How to create a function to get sum of Colors from given array in php

How to create a function to get sum of Colors given in this array.
This is my array-
$sales = array(
'FIRST'=> array('RED'=> array(9,3),'GREEN'=> array(4,5,8,2)),
'SECOND'=> array('RED'=> array(3,5,5,2),'YELLOW'=> array(4,2,5)),
'THIRD'=> array('BLUE'=> array(1,2,4),'RED'=> array(9,4,6)),
'FOUR'=> array('BLUE'=> array(2,3,3,5),'BLACK'=> array(4,5,8,9))
);
Expected output:
('RED'=>21,'GREEN=>'..etc)
You are not responding with any message, from your Expected output here is a solution. Make two loops for getting the color array value with the key, now each color has another array and from that you need to pick the first element and add into the color index of another array.
$output = array();
foreach($sales as $val){
foreach($val as $key => $value){
if(isset($output[$key]))
$output[$key] += $value[0];
else
$output[$key] = $value[0];
}
}
print_r($output); // Array ( [RED] => 21 [GREEN] => 4 [YELLOW] => 4 [BLUE] => 3 [BLACK] => 4 )
Check this, I think this is helpful to you.

How do I get value of specific array element by secondary key?

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

Search multidimensional array by specific key and print the value php

I'm trying to print array. All code working fine with foreach loop. But I'm trying to print with associated keys. Is it possible?
Example: key['user_id'] this will print all user_id from array. is it possible? please help me thanks
Array
(
[Post1] => Array
(
[id] => 1
[title] => hi
)
[Post2] => Array
(
[0] => Array
(
[user_id] => 1
)
[1] => Array
(
[user_id] => 2
)
)
[Post3] => Array
(
[0] => Array
(
[user_name] => 1
)
)
)
Here is my PHP code:
foreach($post as $key => $value) {
foreach($value as $print => $key) {
if (is_array($key)){
foreach($key as $print2 => $key2) {
echo "<br>".$key2;
}
}else{
echo "<br>".$key;
}
}
}
You can print_r to achive the same results you want with your triple for each.
I'm trying to print array. All code working fine with foreach loop. But I'm trying to print with associated keys. Is it possible?
You can easily use recursion for such a problem. You can use something along the lines of:
function printValuesByKey($array, $key) {
if (!is_array($array)) return;
if (isset($array[$key]))
echo $key .': '. $array[$key] .'<br>';
else
foreach ($array as $v)
printValuesByKey($v, $key);
}
In your example:
printValuesByKey($array, 'user_id');
will print:
user_id: 1
user_id: 2

Categories