简体   繁体   中英

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],
];

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'];

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM