Search code examples
phparraysmultidimensional-array

Print 2d array data on separate lines with all row values indented except for the first value in each row


This loop

$demo = array();
for($i=0;$i<count($big_array);$i++){
    echo 'Page['.$i.'][0]: '.$big_array[$i][0].'<br>';
    for($j=1;$j<count($big_array[$i]);$j++){
        
        echo 'Email['.$i.']['.$j.']: '.$big_array[$i][$j].'<br>';
        $demo[$big_array[$i][$j]][] = $big_array[$i][$j-1]; //something is not ok with this
    }
}

gives me this:

Page[0][0]: http://www.example.com/impressum
Email[0][1]: [email protected]
Email[0][2]: [email protected]
Page[1][0]: http://www.example.com/termsofuse
Email[1][1]: [email protected]
Email[1][2]: [email protected]
Email[1][3]: [email protected]
Email[1][4]: [email protected]
Page[2][0]: http://www.example.com/adpolicy
Email[2][1]: [email protected]
Email[2][2]: [email protected]
Email[2][3]: [email protected]
Email[2][4]: [email protected]

How can I transform it to get this result:

[email protected]
  http://www.example.com/impressum
[email protected]
  http://www.example.com/impressum
  http://www.example.com/termsofuse
  http://www.example.com/adpolicy
[email protected]
  http://www.example.com/termsofuse
[email protected]
  http://www.example.com/termsofuse
[email protected]
  http://www.example.com/termsofuse
  http://www.example.com/adpolicy
[email protected]
  http://www.example.com/adpolicy
$big_array = [
    [
        'http://www.example.com/impressum',
        '[email protected]',
        '[email protected]',
    ],
    [
        'http://www.example.com/termsofuse',
        '[email protected]',
        '[email protected]',
        '[email protected]',
        '[email protected]',
    ],
    [
        'http://www.example.com/adpolicy',
        '[email protected]',
        '[email protected]',
        '[email protected]',
        '[email protected]',
    ]
];

Solution

  • $array = array ( 0 => array ( 0 => 'http://www.example.com/impressum', 1 => '[email protected]', 2 => '[email protected]', ), 1 => array ( 0 => 'http://www.example.com/termsofuse', 1 => '[email protected]', 2 => '[email protected]', 3 => '[email protected]', 4 => '[email protected]', ), 2 => array ( 0 => 'http://www.example.com/adpolicy', 1 => '[email protected]', 2 => '[email protected]', 3 => '[email protected]', 4 => '[email protected]', ), );
    
    print_r($array);
    
    $final = array();
    foreach ( $array as $group )
    {
        for ( $i=1; $i<count($group); $i++ )
        {
            $final[$group[$i]][] = $group[0];
        }
    }
    
    print_r($final);
    

    Here is the PHP Playground result.

    To format it like your example:

    foreach ( $final as $email => $links )
    {
        echo $email . "\n";
        foreach ( $links as $link )
        {
            echo "  " . $link . "\n";
        }
    }