-1

I have an associative array and want to repeat values to match each array inside the main array, i even dont know how to better explain what i need to accomplish, but the picture below showing exactly what i want to do. here is the array:

$dd = array();
$dd['Type'] = array('Fitted Case/Skin', 'Housing');
$dd['Compatible Model'] = array('For Apple iPhone 5', 'For Apple iPhone 5s','For Alcatel Pixi 4','For Alcatel Pixi 4 Plus Power');

Notice that both arrays has different count of values, i need to loop each array and create a html table with Main Array Keys as Headers and loop thru each array for table rows, but i need to match the count and repeat the missing values. i am sorry for bad explanation, but i tried my best, here exactly how i want it Html Table

I found the solution here

Mustafa Najm
  • 1
  • 1
  • 4

2 Answers2

0

This will loop through the entire first array, and for each first array print all the types.

foreach($dd['Type'] as $type){
  foreach($dd['Compatible Model'] as $phone){
    echo "$type -> $phone";
  }
}

But I really suggest you'll look at a proper data structure. And another piece of advice. Don't use complex array keys. No caps, no spaces.

You should store data in your database like:

product | id | name 
phone   | id | name | id_of_product_it_supports_and_for_each_support_a_new_entry

Then merge it with table joining, and get specific results for each product.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38
  • Thank you, the problem is that array generated dynamically and wont know what the keys will be.. – Mustafa Najm Jul 04 '18 at 00:24
  • The idea is allow user to create variations for ebay, these array keys are the attributes what user will select, it could be up to five attributes, no database table here, the array will be created from a multi-select list for each attribute to select values, then at the next page i need to show a table for each one to assign a SKU for each attribute – Mustafa Najm Jul 04 '18 at 00:27
  • If you don't know the keys, reindex with `$dd = array_values($dd)`, then you can do `$dd[0]` and `$dd[1]` instead of `$dd['Some Key Name']` but it sounds to me you're not using an API. You can't code something for the unpredictable. – Xorifelse Jul 04 '18 at 00:33
  • Thank you, solution found here https://stackoverflow.com/questions/20835464/loop-on-attributes-to-create-inventory-variations – Mustafa Najm Jul 04 '18 at 01:54
0

I think what you need is something like this:

$dd = array();
$dd['color'] = array('Red', 'black', 'white');
$dd['model'] = array('iphone', 'samsung');

foreach($dd['model'] as $model) {
    foreach($dd['color'] as $color) {
        print_r($model . ': ' . $color . PHP_EOL);
    }
}

The output is a table like this:

iphone: Red
iphone: black
iphone: white
samsung: Red
samsung: black
samsung: white
yvoloshin
  • 378
  • 6
  • 18