在php中转换多维数组

时间:2015-06-14 06:27:32

标签: php

此循环

$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
    }
}

给了我这个:

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

如何对其进行转换以获得此结果:

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

的var_dump($ big_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', ), )

1 个答案:

答案 0 :(得分:1)

bool hasSel1 = txt_sel1.Text != "";
bool hasSel2 = txt_sel2.Text != "";
bool hasSel3 = txt_sel3.Text != "";
bool hasSel4 = txt_sel4.Text != "";
bool hasSel5 = txt_sel5.Text != "";

if (!hasSel1 && (!hasSel2 || !hasSel3 || !hasSel4 || !hasSel5)
{
    ...
}

Here是PHP Playground的结果。

像你的例子一样格式化它:

$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);