'How to get multiple values with same key from an array PHP
I have an array where a key has multiple values. The key is the width of a product and the values are optional prices. The customer first chooses a width and than the options. How can I select the options from the array if a width is chosen? One of the first three columns is always chosen and then the other columns are optional. It should be possible to ad up the chosen values.
$pricelist = [
["w70" => 573, 706, 895, 49, 270, 334, 65],
["w80" => 649, 801, 1017, 55, 307, 372, 65],
["w100" => 801, 990, 1260, 69, 384, 449, 76],
["w120" => 909, 1136, 1460, 81, 461, 525, 86],
];
Solution 1:[1]
if you want get array data with specific keys first you need change your array structure to
$pricelist = [
"w70" => [573, 706, 895, 49, 270, 334, 65],
"w80" => [649, 801, 1017, 55, 307, 372, 65],
"w100" => [801, 990, 1260, 69, 384, 449, 76],
"w120" => [909, 1136, 1460, 81, 461, 525, 86],
];
and than you can get data with specific key , example
$pricelist['w70'];
Solution 2:[2]
I found the solution by using a $$ variable variable. Maybe it is a bit strange but it works. I used $$baseprice = $pricelist[$width][$height]. This enables me to get any key value pair from the array. For example $width = "w70" and $height = 1, this returns 706. If there is a better way, please share. I thought i was wrong but i was mistaken. This is not the best solution.The first answer is what i was looking for after all.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gev99 |
Solution 2 |