returning the min array value index - php

I Am trying to compare 3 different array prices in order to find the lowest so that I can decide which array values should be input into a database, the code looks something like this at the moment...
$array_a = array(
"id" => 398,
"price" => 100
);
$array_b = array(
"id" => 387,
"price" => 60
);
$array_c = array(
"id" => 127,
"price" => 50
);
if($array_a && $array_b && $array_c){
$newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
array_keys($newArr, min($newArr));
print_r($newArr)."\n";
}
The above code does not return the correct index of the array with the lowest price which in this case would be 2 (array_c), what would be the correct way to find out the key of the lowest value.
Also what would be the best way to make sure that only numbers are compared with the min() function as opposed to strings?

You can automate it for example in this manner:
$newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
asort($newArr, SORT_NUMERIC);
echo "Minimum: ".reset($newArr).", given in array #".key($newArr);
I 'm not so sure how to answer your closing question -- what should happen if the values are not actually typed as numbers?
Update: Here's one way to exclude non-numeric values:
asort($newArr, SORT_NUMERIC);
while (!is_numeric(current($newArr))) next($newArr);
if (key($newArr) === null) {
echo "No valid elements found";
}
else {
echo "Minimum: ".current($newArr).", given in array #".key($newArr);
}

You can do:
$newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
sort($newArr);
$lowest = array_shift($newArr);

Try this:
$keys = array_keys($your_array);
asort($keys);
$min = $keys[0];
echo "Smallest index: ".$min;

<?php
$array_a = array(
"id" => 398,
"price" => 100
);
$array_b = array(
"id" => 387,
"price" => 60
);
$array_c = array(
"id" => 127,
"price" => 50
);
if($array_a && $array_b && $array_c){
$newArr = array($array_a['price'], $array_b['price'], $array_c['price']);
$key_min = array_keys($newArr, min($newArr));
echo $key_min[0];
}
?>

Related

PHP adding values inside multidimensional array

Please find below the code sample for adding repeated values inside inner array. Can anyone suggest an alternative way to add the values faster? The code will work with smaller arrays, but I want to add big arrays that contain huge amount of data. Also I want to increase execution time.
<?php
$testArry = array();
$testArry[0] = array(
"text" => "AB",
"count" => 2
);
$testArry[1] = array(
"text" => "AB",
"count" => 5
);
$testArry[2] = array(
"text" => "BC",
"count" => 1
);
$testArry[3] = array(
"text" => "BD",
"count" => 1
);
$testArry[4] = array(
"text" => "BC",
"count" => 7
);
$testArry[5] = array(
"text" => "AB",
"count" => 6
);
$testArry[6] = array(
"text" => "AB",
"count" => 2
);
$testArry[7] = array(
"text" => "BD",
"count" => 111
);
$match_key = array();
$final = array();
foreach ($testArry as $current_key => $current_array) {
$match_key = array();
foreach ($testArry as $search_key => $search_array) {
$key = '';
if ($search_array['text'] == $current_array['text']) {
$match_key[] = $search_key;
$key = $search_array['text'];
if (isset($final[$key])) {
$final[$key] += $search_array['count'];
} else {
$final[$key] = $search_array['count'];
}
}
}
for ($j = 0; $j < count($match_key); $j++) {
unset($testArry[$match_key[$j]]);
}
}
print_r($final);
?>
Anyway to add memory during the execution time?
Thank you.
One array_walk will be enough to solve your problem,
$final = [];
array_walk($testArry, function($item) use(&$final){
$final[$item['text']] = (!empty($final[$item['text']]) ? $final[$item['text']] : 0) + $item['count'];
});
print_r($final);
Output
Array
(
[AB] => 15
[BC] => 8
[BD] => 112
)
Demo
array_walk — Apply a user supplied function to every member of an array
array_map() - Applies the callback to the elements of the given arrays
array_key_exists() - Checks if the given key or index exists in the array
You can use array_walk and array_key_exists to iterate through the array element and sum the one which has text index same
$res = [];
array_map(function($v) use (&$res){
array_key_exists($v['text'], $res) ? ($res[$v['text']] += $v['count']) : ($res[$v['text']] = $v['count']);
}, $testArry);

PHP comparing all value inside column of multidimensional array with variable

I have a multidimensional array and a variable to compare:
$var = 1;
$arr = array(
0 => array(
'id' => 5
'NumberAssigned' = 1
),
n => array(
'id' => 22
'NumberAssigned' = 1
)
)
I want to compare all of the value inside the NumberAssigned column in the multidimensional array with the variable, if all of the value in column match with the variable then $var = $var+1. What is the solution?
One option is using array_column to make the multidimensional array into a simple array. Use array_unique to get the unique values. If there are only 1 unique value and the value is the same with $var, all NumberAssigned are the same with $var
$var = 1;
$arr = array(
0 => array(
'id' => 5,
'NumberAssigned' => 1
),
1 => array(
'id' => 22,
'NumberAssigned' => 1
),
2 => array(
'id' => 23,
'NumberAssigned' => 1
),
);
$num = array_unique(array_column($arr,'NumberAssigned'));
if( count($num) === 1 && $num[0] === $var ) $var++;
No need to loop.
Use array_column to get all values and remove duplicates with array_unique.
If the var is in the array and the count is 1 then all values match var.
$narr = array_unique(array_column($arr, "NumberAssigned"));
If(in_array($var, $narr) && count($narr) == 1){
$var++;
}Else{
// They are not all 1
}
Echo $var;
https://3v4l.org/k08NI
You can force uniqueness by using the targeted column as first level keys. As a concise technique when you don't need microoptimization, you can use:
if (count(array_column($arr, null, 'NumberAssigned')) < 2)
// true if $arr is empty or all values in column are the same
This won't be technically fastest. The fastest algorithm would allow an early return before iterating the entire set of data in the column.
function allValuesAreSame($array, $columnName) {
$result = [];
foreach ($array as $row) {
$result[$row[$columnName]] = null;
if (count($result) > 1) {
return false;
}
}
return true; // also true if $array is empty
}

Update value of key in array

I want to multiply the value of all 'imdb' keys by 10 and update the value. In the code below when I print_r $horrorMovies it just shows I have created a new array with the required amounts. Its almost there if i do
$horrorMovies[0]['imdb'] = $imdbPercent;
But the values just get written to the first nested array.
Im not sure how to make this work with foreach, if it is possible.
function imdbMultiply($n) {
return($n['imdb'] * 10);
}
$horrorMovies = array(
array(
"title" => "The babadook",
"imdb" => 6.8,
"rotten" => 98
),
array(
"title" => "The shining",
"imdb" => 8.4,
"rotten" => 87
)
);
$imdbPercent = array_map("imdbMultiply", $horrorMovies);
$horrorMovies['imdb'] = $imdbPercent;
There's a few problems with your code:
Your imdbMultiply function needs to return the $n array, but modified so the imdb key is multiplied by 10.
array_map returns the new array, so you should set $horrorMovies to the result of array_map
In the end, your code should look like this:
function imdbMultiply ($n) {
$n['imdb'] *= 10;
return $n;
}
$horrorMovies = array_map('imdbMultiply', $horrorMovies);
//original data
$horrorMovies = array(
array(
"title" => "The babadook",
"imdb" => 6.8,
"rotten" => 98
),
array(
"title" => "The shining",
"imdb" => 8.4,
"rotten" => 87
)
);
//define "transformation" function, note that the argument is passed via reference
function imdbMultiply(&$n) {
$n['imdb'] *= 10;
}
//one option is to use foreach and then unset the reference to the
//last array element
foreach($horrorMovies as &$v){
$v['imdb'] *= 10;
}
unset($v);
print_r($horrorMovies);
//alternatively, one might apply the "transformation" function
//directly to each array element without the need to create a copy
array_walk($horrorMovies, "imdbMultiply");
print_r($horrorMovies);
You can just foreach the subarray[imdb] items.
$horrorMovies = array(
array(
"title" => "The babadook",
"imdb" => 6.8,
"rotten" => 98
),
array(
"title" => "The shining",
"imdb" => 8.4,
"rotten" => 87
)
);
foreach($horrorMovies as &$subarray){
$subarray["imdb"] *= 10;
}
var_dump($horrorMovies);
https://3v4l.org/ub40E
You just need to go into a loop and change the 'imdb' values, add the next
for loop to your code:
for ($i=0; $i<count($horrorMovies); $i++){
$horrorMovies[$i]['imdb']*=10;
}
If I understand what you expect, your imdbMultiply() function should be the following to be used with array_map :
function imdbMultiply($n) {
$n['imdb'] *= 10;
return $n;
}
Is it what you expect ?
Another idea is to use array_walk function, but you should define your imdbMultiply() function like this :
function imdbMultiply(&$n) {
$n['imdb'] *= 10;
}
The usage of array_walk is different :
array_walk($horrorMovies, "imdbMultiply");
var_dump($horrorMovies);

Search associative array of arrays. How?

My question is how can I search an array built this way? Basically there may be a need to repeat the key and this is what I got so far to maybe solve this. If the price is the same for 2 different items I cannot have 2 keys with the same value.
Please feel free to improve on array layout.
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
Provided there will never be any duplication of the second column, you can do this:
$search = "EA_WTRESRVD"; //value to search for
$price_list = array(
1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")
);
$array = array_column($price_list, 0, 1);
echo $array[$search];
I would suggest that if you have a unique product code (SKU), you should use this to index your array.
$products = [
'EA_WTRESRVD' => [
'name' => '...',
'price' => 9.99,
// ...
],
'EA_WTRESRV' => [
'name' => '...',
'price' => 9.99,
// ...
],
];
Then you can access the price of any product by it's SKU.
$price = $products['EA_WTRESRV']['price'];
Here's one way:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
foreach ($price_list as $arr) {
if (in_array( $search, $arr )) {
echo $search;
}
}
The foreach iterates over the multidimensional array whose elements are each arrays. Each array is inspected by in_array() for the search term.
However, this is not the only way. If you wish to avoid in_array(), you could also code as follows:
<?php
$price_list = [ 1 => array("9.99", "EA_WTRESRVD"),
2 => array("9.99", "EA_WTRESRV")];
$search = "EA_WTRESRV";
$len = strlen($search);
foreach ($price_list as $arr) {
$val = array_values($arr);
foreach($val as $v) {
if ( ( strpos( $v,$search )) !== false) {
if ( strlen($v) == $len) {
echo "$search is in the price list.\n";
}
}
}
}

How do I retrieve a random value in multidimensional associative array?

I have an array which contains information on posts I have made.
$DexArray = array(
array(
'url' => "http://i.imgur.com/ObXLdd6C.jpg",
'headline' => "Dronningens Nytårstale",
'subline' => "Tallene bag talen og årets spilforslag",
'href' => "nytaarstale.php",
'postedby' => "kris",
'postedurl' => "https://www.facebook.com/dataanalyticsdk",
'dato' => "21. december, 2014"
),
array(
'url' => "http://i.imgur.com/sxddhOe.jpg",
'headline' => "Endless Jewelry",
'subline' => "Are there really endless possibilities?",
'href' => "endless.php",
'postedby' => "Nikolaj Thulstrup",
'postedurl' => "kris",
'dato' => "10. december, 2014"
),
It is stored in a multidimensional associate array. I am trying to retrieve a random 'href' value in the array and store it as a variable.
I have tried using the array_rand function but it doesn't seem to work.
$k = array_rand($DexArray);
$v = $array[$k]['href'];
I get an error message saying: undefined variable: array in this line "$v = $array[$k]['href'];"
Do you have a solution for this?
It should be
$k = array_rand($DexArray);
$v = $DexArray[$k]['href'];
Here's a working debug :) link
There was a lingering , in your thingy. And $array was never defined in the first place, so that's what the error was telling you about.
Execute the code it will return the random value from the multidimensional php array.
<?php
$filter_field = array();
$original_items = array(
array(1, 'stuff1', 'info1', 'response1', 'info1', 'response1'), array(2, 'stuff2', 'info2', 'response2', 'info2', 'response2'), array(3, 'stuff3', 'info3', 'response3', 'info3', 'response3'), array(4, 'stuff4', 'info4', 'response4', 'info4', 'response4'));
for ($x = 0; $x < sizeof($original_items); $x++) {
array_push($filter_field, $original_items[$x][0]);
}
shuffle($filter_field);
echo "<br/><br/><br/>";
for ($x = 0; $x < sizeof($original_items); $x++) {
$k = $filter_field[$x];
for ($y = 0; $y < 5; $y++) {
echo $original_items[$k-1][$y];
}
echo "<br/><br/>";
}
?>
Here is another solution that will return the index of the random array.
$var = array(
array("a", "one"),
array("b", "two"),
array("c", "three"),
array("d", "four"),
array("e", "five"),
array("f", "six"),
array("g", "seven")
);
// array_rand returns the INDEX to the randomly
// chosen value, use that to access the array.
$finalVar = $var[array_rand($var)];
print_r($finalVar);

Categories