使用相同的值更改数组键和组键

时间:2014-06-09 04:35:37

标签: php arrays key

我有一个如下所示的数组:

Array
(
[0] => Array
    (
        [variant_name] => Green
        [product_id] => 2
        [variant_id] => 67
        [amount] => 1000
    )

[1] => Array
    (
        [variant_name] => Red
        [product_id] => 2
        [variant_id] => 68
        [amount] => 0
    )
)

预计会是这样的:

Array (
[2] => array (
       [67] => array (
                  [variant_id] => Green
                  [amount] => 1000
                 (   
       [68] => array (
                  [variant_id] => Red
                  [amount] => 0
                 ( 


)

哪个是按product_id分组,然后由variant_id拆分为数组。 我怎样才能做到这一点。 非常感谢你。

2 个答案:

答案 0 :(得分:2)

foreach($values as $product)
{
$newValues[$product["product_id"]][$product["variant_id"]]=
 array(
  'product_name'=>$product["variant_name"],
  'amount'=>$product["amount"]
  );
}

<强>输出

Array
(
    [2] => Array
        (
            [67] => Array
                (
                    [product_name] => Green
                    [amount] => 1000
                )

            [68] => Array
                (
                    [product_name] => Red
                    [amount] => 0
                )

        )

)

注意您的原始数组中有variant_name,并且您在输出中将其用作variant_id。您可以在此代码中使用索引。我只是用了似乎匹配的东西。

答案 1 :(得分:1)

一个简单的foreach循环就足够了。当然,您需要在新数组中构建它们。请考虑以下示例:(在您预期的示例中,我认为您指的是variant_name

 $values = array( array( 'variant_name' => 'Green', 'product_id' => 2, 'variant_id' => 67, 'amount' => 1000, ), array( 'variant_name' => 'Red', 'product_id' => 2, 'variant_id' => 68, 'amount' => 0, ), );

$new_values = array();
foreach($values as $key => $value) {
    $new_values[$value['product_id']][$value['variant_id']] = array(
        'variant_name' => $value['variant_name'],
        'amount' => $value['amount'],
    );
}

echo '<pre>';
print_r($new_values);
echo '</pre>';

Sample Output