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];
}
}
}
Related
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
This question already has answers here:
How to search Array for multiple values in PHP?
(6 answers)
Closed 2 years ago.
there is an array like $arr = array(1,2,3,3,3,4,5) . What if we want to get all indexes that have values 3?
i used array_search(3, $arr) but it just give back an integer and just the first index that has value '3'
how can we get an array like $indexes = array(2,3,4) that shows all indexes that have value 3?
your help will be highly appreciated
You can use array_keys with search value PHP Doc
Demo
array_keys($arr,3)
array_keys() returns the keys, numeric and string, from the array.
If a search_value is specified, then only the keys for that value are
returned. Otherwise, all the keys from the array are returned.
you can use array_keys:
foreach (array_keys($arr) as $key) if ($arr[$key] == 3) $result[] = $key;
With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped.
$a = [1,2,3,4,3,3,5,6];
$threes = array_filter($a, function($v, $k) {
return $v === 3 ? $k : false; },
ARRAY_FILTER_USE_BOTH
);
$threes Is an array containing all keys having the value 3.
array(3) { 2, 4, 5 }
This question already has answers here:
How to filter an array by a condition
(9 answers)
get specific column with specific condition from multidimensional array using array function only in php
(4 answers)
Closed 3 years ago.
I have a multi-column PHP array as
Array (
Array ('col1', 'col2', 'col3'),
);
How can I get an array of col2 if col1 is greater than a specific value?
I can do it by a foreach loop, but I think it should be possible with a native function like array_filter.
Simply put, you're better with a foreach loop, as you're not going to have to make multiple iterations of the array. You want to both filter and modify the array, which requires using both array_filter() and array_map() in order to get what you want:
<?php
$arr = [
[5, 'col2-1', 'col3'],
[10, 'col2-2', 'col3']
];
$res = array_filter($arr, function($item) {
return $item[0] > 7;
});
$res = array_map(function($item) {
return $item[1];
}, $res);
var_dump($res);
Test here: https://3v4l.org/HRTOJ
This question already has answers here:
How to combine two arrays together?
(3 answers)
Closed 8 years ago.
To start off, let's look at the arrays -
$array1 = array('user#email.com','user2#email.com','user3#email.com'); // Imagine this has over a million users
$array2 = array('domain1.com','domain2.com'); // This may have between 10-20 domains
What I want to do is loop through the users and continuously assign a domain in the second array to a user in the first array. It should look like this when completed -
$finished = array('user#email.com' => 'domain1.com', 'user2#email.com' => 'domain2.com', 'user3#email.com' => 'domain1.com');
How can I loop through $array1 and sequentially assign a domain from $array2 to each user?
This is mind boggling me right now.
Just FYI array_combine() from the "Duplicate Answer" is incorrect to this answer. The correct answer is below. If $array1 has 5,000,000 emails in it and $array2 has 10 domains in it, the finished array would only give the first 10 items in the array a corresponding domain. Those who marked it duplicate did not read the full description, or do not understand PHP.
Similar to Barmar's, but using the key:
$count = count($array2);
foreach($array1 as $key => $value) {
$finished[$value] = $array2[$key % $count];
}
This works with your posted arrays, however if you have lets say all even or all odd keys in $array1 this would bomb, also with an associative array.
Increment an index in $array2 modulo its size as you assign values.
$index = 0;
$finished = array();
foreach ($array1 as $email) {
$finished[$email] = $array2[$index];
$index = ($index + 1) % count($array2);
}
Make a loop over the larger set. Keep a secondary index variable, and each iteration, increment it, then set it to its value modulo the size of the smaller set. Use this secondary index as the index into your second set to assign to the element from the first set.
This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
I've got 6 arrays - 1 with name and 5 with some properties - which should be assigned to that name. All values are of course in order. I'd like to make a 2-dimensional array with will be later put into CSV and the result should be as on the table here:
I guess that i have to do 2 loops here, but I can't make them work. How to construct such array?
Solution found
I've connected all arrays:
$final_array = array($nazwa_array,$new_ilosc_array,$new_koszt_array,$new_cena_lifo_array,$new_cena_fifo_array,$new_rodzaj_array);
I've found a matrix transposition function, which returns array in correct order:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$a = array();
foreach ( $names AS $key => $value ) {
$a[$key]['name'] = $value;
$a[$key]['property1'] = $value.'->'.$property1_array[$key];
$a[$key]['property2'] = $value.'->'.$property2_array[$key];
$a[$key]['property3'] = $value.'->'.$property3_array[$key];
$a[$key]['property4'] = $value.'->'.$property4_array[$key];
$a[$key]['property5'] = $value.'->'.$property5_array[$key];
}