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

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

Related

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.

PHP generate one array index with many values and remove empty array values

I have this array:
[docs] => Array
(
[indexone] => Array ( [0] => P008062518 )
[indextwo] => Array ( [0] => )
[indexthree] => Array ( [0] => 0000141334 )
[indexfour] => Array ( [0] => P006871638 )
[indexfive] => Array ( [0] => 0000910067 )
[indexsix] => Array ( [0] => )
)
I need to end with this one, extracting all values from the given key:
[docValues] => Array
(
[indexone] => Array ( P008062518, 0000141334, P006871638, 0000910067 )
)
I try this loop but i end with the same array structure :
foreach($values as $key => $data)
{
if(array_key_exists('docs', $data) )
{
$filtered = array_filter($data['docs'], function($var) { return !empty($var);});
$numDocs = array_values($filtered);
$values[$key]['docValues'] = $numDocs;
}
}
How can it be done ?
To get that exact array output:
$result['docValues'][key($values['docs'])] =
array_filter(array_column($values['docs'], 0));
Get the first key to use it as your new key with key()
Get an array of all values in the 0 indexes with array_column()
Remove empty elements using array_filter()
If your first array is called $docArray, then you can do the following:
$docValuesArray = array();//declaring the result array
$indexoneArray = array();//declaring the array you will add values
//to in the foreach loop
foreach ($docArray as $value)
{
$indexoneArray[] = $value[0];//giving each of the values
//found in $docArray to the $indexoneArray
}
$docValueArray[] = $indexoneArray;//adding the $indexoneArray
//to the $docsValueArray
Let me know if that worked for you.
This should do the trick for you:
$docs = [
'indexone' => ['P008062518'],
'indextwo' => [ ],
'indexthree' => ['0000141334'],
'indexfour' => ['P006871638'],
'indexfive' => ['0000910067'],
'indexsix' => [ ],
];
$allDocs = array();
foreach($docs as $key => $doc) {
$docString = implode("<br>",$doc);
if (empty($docString)) {
continue;
}
$allDocs[] = $docString;
}
$allDocsString = implode("<br>",$allDocs);
echo($allDocsString);
P0080625180000141334P0068716380000910067
Simply do this:
Your array
$arr = array("docs" =>
array(
'indexone' => array('P008062518'),
'indextwo' => array(''),
'indexthree' => array('0000141334'),
'indexfour' => array('P006871638'),
'indexfive' => array('0000910067'),
'indexsix' => array('')
)
);
Process:
echo '<pre>';
$index = key($arr["docs"]);
$output['docValues'][$index] = implode('<br/>', array_filter(array_column($arr['docs'], 0)));
print_r($output);
Explanation:
key = key function Returns the first index.
implode = collapse all the array items with the delimiter of <br/>
array_filter = filters the values of an array using a callback
function.
array_column = returns the values from a single column in the input
array.
Result:
Array
(
[docValues] => Array
(
[indexone] => P008062518<br/>0000141334<br/>P006871638<br/>0000910067
)
)
use array_filter() function . if you pass array in array_filter then remove all empty and NULL data record

Replace value in array based on other array

I would like to replace the value of a multidimensional array if a corrosponding array contains a certain value.
Basically, I have two multidimensional arrays. One contains the actual data and the other contains a yes/no for whether the first array should be modified.
Is there any way to do this:
if optB[i][i] contains 'yes'
then opt[i][i] = '<strong>'.opt[i][i].'</strong>';
I'm lost as to whether this is even possible. Any help would be greatly appreciated -- thank you!
Thank you for the help so far. Here is the array:
[opt] => Array
(
[0] => Array
(
[0] => value1
[1] => value2
)
[1] => Array
(
[0] => value3
[1] => value4
)
)
[optB] => Array
(
[0] => Array
(
[0] => on
)
[1] => Array
(
[1] => on
)
)
Those are some interesting arrays because usually numeric arrays always have a 0. I imagine you may have some different key combination so I think this is the best "future-proof" method:
foreach ($optB as $i => $optB2) {
foreach ($optB2 as $j => $val) {
if ($val) {
$opt[$i][$j] = '<strong>' . $opt[$i][$j] . '</strong>';
}
}
}
It is possible. You can do this:
for ($i = 0; $i < count(opt); $i++) {
if ($optB[$i][$i] == "yes")
opt[$i][$i] = '<strong>'.opt[$i][$i].'</strong>';
}
It can be written like this:
if (strpos($optB[$i][$i], 'yes'))
$opt[$i][$i] = '<strong>'.$opt[$i][$i].'</strong>';
Something along these lines:
foreach ($opt as $i => &$arr) {
foreach ($arr as $j => &$val) {
if ($optB[$i][$j]) {
$val = "<strong>$val</strong>";
}
}
}
Modify as needed.

most common values in a multidemensional array

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.

Specifying object in PHP Array from JSON

I'm trying to use a specific object type from a JSON feed, and am having a hard time specifying it. Using the code below I grab and print the specific array (max) I want,
$jsonurl = "LINK";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json,true);
$max_output = $json_output["max"];
echo '<pre>';
print_r($max_output);
echo '</pre>';
And from the Array below, all I want to work with is the [1] objects in each array. How can I specify and get just those values?
Array
(
[0] => Array
(
[0] => 1309924800000
[1] => 28877
)
[1] => Array
(
[0] => 1310011200000
[1] => 29807
)
[2] => Array
(
[0] => 1310097600000
[1] => 33345
)
[3] => Array
(
[0] => 1310184000000
[1] => 33345
)
[4] => Array
(
[0] => 1310270400000
[1] => 33345
)
[5] => Array
(
[0] => 1310356800000
[1] => 40703
)
Well you could fetch those values with array_map:
$max_output = array_map(function($val) { return $val[1]; }, $json_output["max"]);
This requires PHP 5.3, if you use an earlier version, then you can use create_function to achieve similar results:
$max_output = array_map(create_function('$val', 'return $val[1];'), $json_output["max"]);
When you need to create new array which will contain only second values, you may use either foreach loop which will create it or use array_map() (just for fun with anonymous function available since php 5.3.0):
$newArray = array_map( function( $item){
return $item[1]
},$array);
Then you want to use last ("max" -> considering array with numeric keys) item, you can use end():
return end( $item);
And when you can process your data sequentially (eg. it's not part of some big getData() function) you can rather use foreach:
foreach( $items as $key => $val){
echo $val[1] . " is my number\n";
}
After you get $max_output...
for( $i = 0; $i < length( $max_output ); $i++ ) {
$max_output[$i] = $max_output[$i][1];
}
try this:
$ones = array();
foreach ($max_output as $r)
$ones[] = $r[1];

Categories