简体   繁体   中英

Change array key and group key with the same value

I have an array looks like this:

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
    )
)

This expected to be like this:

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


)

Which is group by product_id and then split into arrays group by variant_id. How can I do that. Thank you so much.

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

Output

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

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

        )

)

Note You have variant_name in your original array and you are using that as variant_id in your output. You can play with indexes in this code. I just used what seemed to match.

A simple foreach loop should suffice. Of course, you need to build them inside a new array. Consider this example: (In your expected example, I think you were referring to 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

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