使用组合将数组作为URL参数传递

时间:2017-02-25 12:07:13

标签: php arrays

我有点被困在这里。 我正在尝试为以下产品变体构建URL:

&brand=6&color=11,12,etc

那么如何将数组的键组合成一个字符串,如上所述

此外,如果你能建议我另一种方法来达到预期的效果。 非常感谢你!

2 个答案:

答案 0 :(得分:0)

首先必须结合"品牌"的价值观。使用" color"的值。之后,您可以将它们一起输出:

<?php

$columns = [
    'brand' => [
        ['b1A', 'b1B'],
        ['b2A', 'b2B'],
    ],
    'color' => [
        ['c1A', 'c1B'],
        ['c2A', 'c2B'],
    ],
];

$data = [];
foreach ($columns as $title => $rows) {
    foreach ($rows as $id => $values) {
        if (!isset($data[$id])) {
            $data[$id] = [];
        }

        $data[$id][$title] = $values;
    }
}

foreach ($data as $row) {
    $output = '';
    foreach ($row as $key => $values) {
        $output .= '&' . $key . '=' . implode(',', $values);
    }

    echo $output . '<br/>' . PHP_EOL;
}

答案 1 :(得分:0)

<?php
$filters = [
    "brand" => [
        1 => "Adidas",
        2 => "Puma"
    ],
    "color" => [
        1 => "White",
        2 => "Blue",
        3 => "Red",
        4 => "Yellow"
    ]
];


foreach($filters['brand'] as $key => $val){
    foreach($filters['color'] as $k => $v){
       echo "brand=$key,$val&color=$k,$v" . PHP_EOL;
       echo "brand=$val&color=$v" . PHP_EOL;
    }
}

输出

brand=1,Adidas&color=1,White
brand=Adidas&color=White
...

示例2;

foreach($filters['brand'] as $key => $val){
   echo "&brand=$key,$val&color=" . implode(',',$filters['color']) . PHP_EOL;
}

&brand=1,Adidas&color=White,Blue,Red,Yellow
&brand=2,Puma&color=White,Blue,Red,Yellow