-2

I want to display data from an array. I had an array like this :

   Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

I try with this script :

$product = array('a','b','c','d');
echo '<table border="1">';
    echo '<tr><th>Product 1</th><th>Product 2</th><th>Similarity</th></tr>';
    for($i=0; $i<count($product); $i++){
        echo '<tr><td>'.$product[$i].'</td><td>'.$product[$i+1].'</td></tr>';
    }
    echo '</table>';

but I'm confused and tried but always wrong to get an output in table as follows :

| Data 1 | Data 2 |
| a      | b      |
| a      | c      | 
| a      | d      |
| b      | c      |
| b      | d      |
| c      | d      |

and so on according to the length of the array

  • 1
    please show us what you've tried! – Jeff Sep 10 '18 at 18:21
  • 1
    also please specify what the patterns should be - I can't find one. _EDIT_: I found it... – Jeff Sep 10 '18 at 18:22
  • 1
    We are always glad to help and support new coders but ***you need to help yourself first. :-)*** After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Sep 10 '18 at 18:22
  • I've edited my question – Muh Fadly Sangadji Sep 10 '18 at 18:25

2 Answers2

1

You can will need to use multiple loops to get the output you are looking for:

<?php

$a = [
    0 => "a",
    1 => "b",
    2 => "c",
    3 => "d"
];

echo '<table border="1">';
echo '<tr><th>Product 1</th><th>Product 2</th><th>Similarity</th></tr>';

foreach($a as $key => $value)
{
    for($i = $key + 1; $i < count($a); $i++)
    {
        echo "<tr><td>$value</td><td>{$a[$i]}</td></tr>";
    }
}

echo '</table>';

The result will be:

enter image description here

Gary Thomas
  • 2,147
  • 1
  • 7
  • 19
1

You need to loop the array twice nested.
The first loop runs the full array, the other uses array_slice to only get "+1" and on values.

$product = array('a','b','c','d');
echo '<table border="1">';
echo "<tr><th>Product 1</th><th>Product 2</th><th>Similarity</th></tr>\n";

foreach($product as $key => $a){
    foreach(array_slice($product, $key+1) as $b){
        echo '<tr><td>'.$a.'</td><td>'.$b."</td></tr>\n";
    }
}
echo '</table>';

Output:

<table border="1">
<tr><th>Product 1</th><th>Product 2</th><th>Similarity</th></tr>
<tr><td>a</td><td>b</td></tr>
<tr><td>a</td><td>c</td></tr>
<tr><td>a</td><td>d</td></tr>
<tr><td>b</td><td>c</td></tr>
<tr><td>b</td><td>d</td></tr>
<tr><td>c</td><td>d</td></tr>
</table>

https://3v4l.org/fdp2e

Andreas
  • 24,301
  • 5
  • 27
  • 57