how to calculate two values in array_map function [duplicate] - php

This question already has answers here:
Sum values of multidimensional array by key without loop
(5 answers)
Closed 10 months ago.
How can I calculate the value of one string containing few values?
For example,
$toPluck = 'price';
$arr = $gamesWorth;
$plucked = array_map(function($item) use($toPluck) {
echo $item[$toPluck];
}, $arr);
The webpage displays 2, 20, and 50.
I want to calculate them both and echo to the page 72.
I tried to find a solution on the web and on that website, but I can't find it..

Seems like a job for array_reduce
$toPluck = 'price';
$arr = array(
array('price' => 2),
array('price' => 20),
array('price' => 50),
);
echo array_reduce($arr, function($sum, $item) use($toPluck) {
return $sum + $item[$toPluck];
}, 0);

There are a few ways to handle it, but a simple modification to your existing code would be to return values from your array_map() and sum the resultant array with array_sum().
$toPluck = 'price';
$arr = $gamesWorth;
$plucked = array_map(function($item) use($toPluck) {
// Uncomment this if you want to print individual values
// Otherwise the array_map() produces no output to the screen
// echo $item[$toPluck];
// And return the value you need
return $item[$toPluck];
}, $arr);
// $plucked is now an array
echo array_sum($plucked);

Related

Multiple values in array excluding specified key [duplicate]

This question already has answers here:
Deleting an element from an array in PHP
(25 answers)
Closed 9 months ago.
I'm trying to verify if certain values exist within an array excluding a specific key:
$haystack = array(
"id" => 1,
"char1" => 2,
"char2" => 3,
"char3" => 4,
);
$needles = array(2, 4);
Solution that I found here: in_array multiple values
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
The problem is that I'm checking if certain chars exist within the array. This will work fine in this case:
$exists = in_array_all([2, 4], $haystack); // true
But it'll cause an issue in this situation:
$exists = in_array_all([1, 3], $haystack); // true
It found the value 1 in the key id and therefor evaluates as true while a char with id 1 is not within the array. How can I make it so that it excludes the key id within the search?
Note: This is example data. The real data is much larger, so just using if / else statements isn't really viable.
function in_array_all($needles, $haystack) {
return empty(array_diff($needles, $haystack));
}
function excludeKeys($haystack){
$tempArray = array();
foreach($haystack as $key => $value){
if ($key == "id"){
// Don't include
}else{
$tempArray[$key] = $value;
}
}
return $tempArray;
}
$haystack = array(
"id" => 1,
"char1" => 2,
"char2" => 3,
"char3" => 4,
);
$exists = in_array_all([1, 3], excludeKeys($haystack));
echo("Exists: ".($exists ? "Yes" : "No"));
This basically just returns the array without the keys you specify. This keeps the original array in tact for later use.
Edit:
These bad solutions are really a symptom of a problem in your data structure. You should consider converting your array to an object. It looks like this:
$object = new stdClass();
$object->id = 1;
$object->chars = array(2, 3, 4);
$exists = in_array_all([1, 3], $object->chars);
This is how you're supposed to separate your data up. This way you can properly store your information by key. Furthermore you can store other objects or arrays within the object specific to a key, as shown above.
Unset id index and then do search:
function in_array_any($needles, $haystack) {
unset($haystack['id']);
return !array_diff($needles, $haystack);
}
https://3v4l.org/PTjOS

How to allow same keys in one array? [duplicate]

This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 4 years ago.
I need to add the same keys to the array, but with different values,
foreach ($selections as $selection) {
$array += [$selection['option_id']=>$selection['product_id']];
}
// example output
$array = [30=>12,14=>10],
but really it should be
[30=>7,30=>12,14=>10];
When the key repeats, it merges.
You just can't.
But you can make the value of this key an array.
So you'll have
$array = [30=>[7,12],14=>10];
You can use any array functions on $array[30]
What you should do is to return the products ids as an array:
$array = array_reduce($selections, function ($carry, $selection) {
if (!isset($carry[$selection['option_id']])) {
$carry[$selection['option_id']] = [];
}
$carry[$selection['option_id']][] = $selection['product_id'];
return $carry;
}, []);
Now the result would be:
[30 => [7, 12], 14 => [10]];
Keys in array are, as the word itself says, keys to access the value they contain and each key must be unique, else you won't have a way to . If you could have two time or more the same value, how could you tell which will access one value and which one will access the other one? To solve your problem you have a way: generate a multidimensional array such that you can have multiple value stored "behind" a single key. E.g. [30 => [7,12], 14 => 10]
Based on your code you can just create a double loop with a nested foreach to navigate through all the value, something like:
foreach ($selections as $selection) {
if(!is_array($selection['product_id']) $array += [$selection['option_id']=>$selection['product_id']];
else {
foreach ($selection['product_id'] as $product) {
$array += [$selection['option_id']=> product];
}
}
}

Display data from multidimensional array [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 5 years ago.
How do I display the individual values from this array?
for instance: X = 8.6; Y = 43; F = more stuff?
$MEGA['Stuff'] = [
8.6,
43,
'more stuff'
];
You could make it an associative array with key-value pair.
$MEGA['Stuff'] = [
'X' => 8.6,
'Y' => 43,
'F' => 'more stuff'
];
foreach ($MEGA['Stuff'] as $k => $v) {
echo $k . ' : '. $v;
echo '<br/>';
}
Adding to Object Manipulator answer, above, in case you cannot manipulate the original array, you could use the array_combine function to set the keys to the array, thus reducing the need of iterating over it twice.
$keys = ["X", "Y", "F"];
$MEGA["Stuff"] = array_combine($keys, $MEGA["Stuff"]);
Now the $MEGA["Stuff"] array is in the form, Object Manipulator has it, and you can manipulate it at your liking
suppose k,y and f is fix therefor use can use following code.
you have 3 characters k,y,f right
arrays count is 3
now you can make code like this
$char=array('k','y','f');
get count of $MEGA['Stuff'];
$count=count($MEGA['Stuff']);
Now we are using for loop.
for($i=0;$i<$count;$i++)
{
echo $char[$i].' = '.$MEGA['Stuff'][$i];echo '<br/>';
}
You can use this code for display value from array.
You can just use echo to display the data:
echo $MEGA['stuff'][0])
echo $MEGA['stuff'][1])
echo $MEGA['stuff'][2])

PHP: How to delete all array elements after an index [duplicate]

This question already has answers here:
php - how to remove all elements of an array after one specified
(3 answers)
Closed 9 years ago.
Is it possible to delete all array elements after an index?
$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
now some "magic"
$myArray = delIndex(30, $myArrayInit);
to get
$myArray = array(1=>red, 30=>orange);
due to the keys in $myArray are not successive, I don't see a chance for array_slice()
Please note : Keys have to be preserved! + I do only know the Offset Key!!
Without making use of loops.
<?php
$myArrayInit = [1 => 'red', 30 => 'orange', 25 => 'velvet', 45 => 'pink']; //<-- Your actual array
$offsetKey = 25; //<--- The offset you need to grab
//Lets do the code....
$n = array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
$count = array_search($offsetKey, $n); //<--- Returns the position of the offset from this array using search
$new_arr = array_slice($myArrayInit, 0, $count + 1, true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);
Output :
Array
(
[1] => red
[30] => orange
[25] => velvet
)
Try
$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);
See demo
I'd iterate over the array up until you reach the key you want to truncate the array thereafter, and add those items to a new - temporary array, then set the existing array to null, then assign the temp array to the existing array.
This uses a flag value to determine your limit:
$myArrayInit = array(1=>'red', 30=>'orange', 25=>'velvet', 45=>'pink');
$new_array = delIndex(30,$myArrayInit);
function delIndex($limit,$array){
$limit_reached=false;
foreach($array as $ind=>$val){
if($limit_reached==true){
unset($array[$ind]);
}
if($ind==$limit){
$limit_reached=true;
}
}
return $array;
}
print_r($new_array);
Try this:
function delIndex($afterIndex, $array){
$flag = false;
foreach($array as $key=>$val){
if($flag == true)
unset($array[$key]);
if($key == $afterIndex)
$flag = true;
}
return $array;
}
This code is not tested

php get two different random array elements [duplicate]

This question already has answers here:
How do I select 10 random things from a list in PHP?
(5 answers)
Closed 8 months ago.
From an array
$my_array = array('a','b','c','d','e');
I want to get two DIFFERENT random elements.
With the following code:
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
}
it is possible to get two times the same letter. I need to prevent this. I want to get always two different array elements. Can somebody tell me how to do that?
Thanks
array_rand() can take two parameters, the array and the number of (different) elements you want to pick.
mixed array_rand ( array $input [, int $num_req = 1 ] )
$my_array = array('a','b','c','d','e');
foreach( array_rand($my_array, 2) as $key ) {
echo $my_array[$key];
}
What about this?
$random = $my_array; // make a copy of the array
shuffle($random); // randomize the order
echo array_pop($random); // take the last element and remove it
echo array_pop($random); // s.a.
You could always remove the element that you selected the first time round, then you wouldn't pick it again. If you don't want to modify the array create a copy.
for ($i=0; $i<2; $i++) {
$random = array_rand($my_array); # one random array element number
$get_it = $my_array[$random]; # get the letter from the array
echo $get_it;
unset($my_array[$random]);
}
You can shuffle and then pick a slice of two. Use another variable if you want to keep the original array intact.
$your_array=[1,2,3,4,5,6,7];
shuffle($your_array); // randomize the order
$your_array = array_slice($your_array, 0, 2); //pick 2
foreach (array_intersect_key($arr, array_flip(array_rand($arr, 2))) as $k => $v) {
echo "$k:$v\n";
}
//or
list($a, $b) = array_values(array_intersect_key($arr, array_flip(array_rand($arr, 2))));
here's a simple function I use for pulling multiple random elements from an array.
function get_random_elements( $array, $limit=0 ){
shuffle($array);
if ( $limit > 0 ) {
$array = array_splice($array, 0, $limit);
}
return $array;
}
Here's how I did it. Hopefully this helps anyone confused.
$originalArray = array( 'first', 'second', 'third', 'fourth' );
$newArray= $originalArray;
shuffle( $newArray);
for ($i=0; $i<2; $i++) {
echo $newArray[$i];
}
Get the first random, then use a do..while loop to get the second:
$random1 = array_rand($my_array);
do {
$random2 = array_rand($my_array);
} while($random1 == $random2);
This will keep looping until random2 is not the same as random1

Categories