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]: sales@example.com
Email[0][2]: support@example.com
Page[1][0]: http://www.example.com/termsofuse
Email[1][1]: support@example.com
Email[1][2]: terms1@example.com
Email[1][3]: terms2@example.com
Email[1][4]: ad2@example.com
Page[2][0]: http://www.example.com/adpolicy
Email[2][1]: support@example.com
Email[2][2]: ad1@example.com
Email[2][3]: ad2@example.com
Email[2][4]: ad1@example.com

How can I transform it to get this result:

sales@example.com
  http://www.example.com/impressum
support@example.com
  http://www.example.com/impressum
  http://www.example.com/termsofuse
  http://www.example.com/adpolicy
terms1@example.com
  http://www.example.com/termsofuse
terms2@example.com
  http://www.example.com/termsofuse
ad2@example.com
  http://www.example.com/termsofuse
  http://www.example.com/adpolicy
ad1@example.com
  http://www.example.com/adpolicy
$big_array = [
    [
        'http://www.example.com/impressum',
        'sales@example.com',
        'support@example.com',
    ],
    [
        'http://www.example.com/termsofuse',
        'support@example.com',
        'terms1@example.com',
        'terms2@example.com',
        'ad2@example.com',
    ],
    [
        'http://www.example.com/adpolicy',
        'support@example.com',
        'ad1@example.com',
        'ad2@example.com',
        'ad1@example.com',
    ]
];

Solution

  • $array = array ( 0 => array ( 0 => 'http://www.example.com/impressum', 1 => 'sales@example.com', 2 => 'support@example.com', ), 1 => array ( 0 => 'http://www.example.com/termsofuse', 1 => 'support@example.com', 2 => 'terms1@example.com', 3 => 'terms2@example.com', 4 => 'ad2@example.com', ), 2 => array ( 0 => 'http://www.example.com/adpolicy', 1 => 'support@example.com', 2 => 'ad1@example.com', 3 => 'ad2@example.com', 4 => 'ad1@example.com', ), );
    
    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";
        }
    }