Create data set in php (loop)

Viewed 56

Hello i am trying to create data set like

Expected output:-

Array
(
    [0] => Array
        (
    [sku] => sku
    [variant_option_one_name] => Color
    [variant_option_one_value] => Cyan
),
   [1] => Array
        (
    [sku] => sku
    [variant_option_one_name] => Color
    [variant_option_one_value] => Red
 )
)

but i am not sure what is missing in code.

Here is the code

$array = array(
    0 => array(
        'id_product_attribute' => '17615',
        'id_product'           => '2295',
        'reference'            => '',
        'available_date'       => '0000-00-00',
        'vend_id'              => null,
        'id_shop'              => '1',
        'id_attribute_group'   => '1',
        'is_color_group'       => '1',
        'group_name'           => 'Color',
        'attribute_name'       => 'Cyan',
        'id_attribute'         => '1',
    ),
    1 => array(
        'id_product_attribute' => '17616',
        'id_product'           => '2295',
        'reference'            => '',
        'available_date'       => '0000-00-00',
        'vend_id'              => null,
        'id_shop'              => '1',
        'id_attribute_group'   => '1',
        'is_color_group'       => '1',
        'group_name'           => 'Color',
        'attribute_name'       => 'Red',
        'id_attribute'         => '21',
    ),
);

$ids = array();
foreach ($array as $combinations) {
    $ids['sku']                      = 'sku';
    $ids['variant_option_one_name']  = $combinations['group_name'];
    $ids['variant_option_one_value'] = $combinations['attribute_name'];
}
print_r($ids);//

Here i am getting

Array
(
    [sku] => sku
    [variant_option_one_name] => Color
    [variant_option_one_value] => Red
)

The above output i am getting. Seems like data is overwrite Any correction to get both the data ? I do not get both the colors in array. It Thankyou

2 Answers

You're absolutely right, the values are being overwritten each time.

What you need to do is, each time you loop you should create a new array containing your values, and then assign that array to a new index inside the main array (so you get an array of arrays, like the expected output you've shown):

foreach ($array as $combinations) {
  $arr = array();
  $arr['sku']                      = 'sku';
  $arr['variant_option_one_name']  = $combinations['group_name'];
  $arr['variant_option_one_value'] = $combinations['attribute_name'];
  $ids[] = $arr;
}

Live Demo: http://sandbox.onlinephpfunctions.com/code/3a0cf7f8cbb994ef4192c1e23493bef397785937

foreach ($array as $combinations) {
  array_push ($ids, [
    'sku' => 'sku',
    'variant_option_one_name' => $combinations['group_name'],
    'variant_option_one_value' => $combinations['attribute_name']
  ]);
}
Related