php数组翻转值作为键,使其变得简单

时间:2014-12-02 00:04:57

标签: php arrays flip

我一直在努力正确地格式化数组 我有这个代码:

    require('simple_html_dom.php');

    $table = array();
    $html = file_get_html('apc.html');
    foreach($html->find('tr') as $row) {

        $rack = ltrim($row->find('td',0)->plaintext);
        $location = ltrim($row->find('td',1)->plaintext);
        $usage = ltrim($row->find('td',2)->plaintext);
        $auk = ltrim($row->find('td',3)->plaintext);
        $cost = ltrim($row->find('td',4)->plaintext);


     $rack = rtrim($rack);
     $location = rtrim($location);

     $usage = rtrim($usage);
     $auk = rtrim($auk);
     $cost = rtrim($cost);

        $table[$rack][$usage][$auk][$cost] = true;

    }
echo '<pre>';
print_r($table);
echo '</pre>';

使用上面的simple_html_dom我可以将html表转换为数组,如下所示:

[Rack01] => Array
        (
            [741,60] => Array
                (
                    [1.409,04] => Array
                        (
                            [267,72] => 1
                        )

                )

            [110,88] => Array
                (
                    [210,67] => Array
                        (
                            [40,03] => 1
                        )

                )

        )

    [Rack 09] => Array
        (
            [843,84] => Array
                (
                    [1.603,30] => Array
                        (
                            [304,63] => 1
                        )

                )

        )

我想得到如下结果:

array(
 [0]  => array (
     [usage] => 'Rack 01',
     [usage] => '741,60',
     [auk] => '1.409.04',
     [cost] => '267,72')
 [1]  => array (
     [usage] => 'Rack 02',
     [usage] => 'value???',
     [auk] => 'value???',
     [cost] => 'value???')

任何帮助都是apreaciate

1 个答案:

答案 0 :(得分:1)

像这样的东西。另请注意,trim将同时执行左右:

foreach($html->find('tr') as $row) {
    $rack     = trim($row->find('td',0)->plaintext);
    $location = trim($row->find('td',1)->plaintext);
    $usage    = trim($row->find('td',2)->plaintext);
    $auk      = trim($row->find('td',3)->plaintext);
    $cost     = trim($row->find('td',4)->plaintext);

    $table[] = array('rack'  => $rack,
                     'usage' => $usage,
                     'auk'   => $auk,
                     'cost'  => $cost);
}