dsj0312 2012-11-20 12:40
浏览 175
已采纳

创建多个数组的数组之一

There are three array of the form:

Array (
    [0] => NAME
    [1] => NAME
    [n] => n
)
Array (
    [0] => DATE
    [1] => DATE
    [n] => n
)
Array (
    [0] => TEXT
    [1] => TEXT
    [n] => n
)

As possible to combine these three arrays in one of the next species?

Array(
    Array (
        [0] => NAME
        [1] => DATE
        [2] => TEXT
    )
    Array (
        [0] => NAME
        [1] => DATE
        [2] => TEXT
    )
        Array (
        [0] => NAME
        [1] => DATE
        [2] => TEXT
    )
    and etc.
)

Arrays build with the use of library PHP Simple HTML DOM Parser Manual that's the way

// Search for the name
$array_nameNews = array();
foreach($html->find('div.narrow_column div h2 a') as $element) {    
    $nameNews = $element->innertext;
    $array_nameNews[] = $nameNews;
}

// Search the date
$array_dateNews = array();
foreach($html->find('div.narrow_column div div.postdate') as $element) {
    $dateNews = $element->innertext;
    $array_dateNews[] = $dateNews;
}

// Search text
$array_textNews = array();
foreach($html->find('div.narrow_column div div.postdate span') as $element) {
    $textNews = $element->innertext;
    $array_textNews[] = $textNews;
}
  • 写回答

5条回答 默认 最新

  • dpd46554 2012-11-20 12:53
    关注

    You can do this with array_merge() and your end-result arrays as others suggest, but you should do this instead:

    $articles = array();
    foreach($html->find('div.narrow_column div') as $art_elem) {
        $article = array(
            'name' => $art_elem->find('h2 a', 0)->plaintext,
            'date' => $art_elem->find('div.postdate', 0)->plaintext,
            'text' => $art_elem->find('div.postdate span')->innertext,
        );
        $articles[] = $article;
    }
    

    Two reasons:

    1. It's much clearer what you are actually trying to accomplish.
    2. It is less brittle. Suppose a particular 'div.narrow_column div' element lacks one of these fields? In this case, your three arrays might be different sizes, or the items in the array may not correspond to other ones with the same index. If you iterate the container elements once and grab the items you need within the $art_elem context, you can degrade gracefully even when some items are missing.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗