来自两个foreach的PHP填充数组

时间:2014-02-08 09:44:57

标签: php arrays

我有一个数组,我想填写2 foreach

preg_match_all('/<div[^>]+class="titr2"[^>]*>\s*<a[^>]+>(.*?)<\/a>\s*<\/div>/si', file_get_contents($handle), $names);


$other = array();

foreach ($names[0] as $value) {

    $pattern = '/<a[^>]*>(.*?)<\/a>/si';
    preg_match($pattern, $value, $matches);

    $name['A'] = $matches[1];
    $other[]   = $name;
}

preg_match_all('/<\/a><\/div>(.*?)\s*<div[^>]+class="toolz"[^>]*>\s*/si',   file_get_contents($handle), $other);
foreach ($other[1] as $value) {

    $default = preg_replace('/<img[^>]*>(.*)\/>/is', "", $value);
    $default = explode('<br />', $default);

    $name['B'] = $default[0];
    $name['C'] = $default[1];
    $other[]=$name;
}
echo"<pre>";print($other);echo"</pre>";

我希望得到这样的结果:

$other = array
(
    0 => array
        (
            'A' => 'aaaaaaaaaaaa',
            'B' => 'bbbbbbbbbbbb',
            'C' => 'cccccccccccc'
        ),
    1 => array
        (
            'A' => 'dddddddddddd',
            'B' => 'eeeeeeeeeeee',
            'C' => 'ffffffffffff'
        ),
    2 => array
        (
            'A' => 'gggggggggggg',
            'B' => 'hhhhhhhhhhhh',
            'C' => 'iiiiiiiiiiii'
        )                
);

更新:

Current Result:

1 个答案:

答案 0 :(得分:2)

preg_match_all('/<div[^>]+class="titr2"[^>]*>\s*<a[^>]+>(.*?)<\/a>\s*<\/div>/si',  file_get_contents($handle), $names);


$result = array('A'=>array(), 'B'=>array(), 'C'=>array());

foreach ($names[0] as $value) {

    $pattern = '/<a[^>]*>(.*?)<\/a>/si';
    preg_match($pattern, $value, $matches);
    foreach ($matches[1] as $match){
        $result['A'][]   = $match;
    }
}

preg_match_all('/<\/a><\/div>(.*?)\s*<div[^>]+class="toolz"[^>]*>\s*/si',   file_get_contents($handle), $other);
foreach ($other[1] as $value) {

    $default = preg_replace('/<img[^>]*>(.*)\/>/is', "", $value);
    $default = explode('<br />', $default);

    $result['B'][] = $default[0];
    $result['C'][] = $default[1];
}
echo"<pre>";print($result);echo"</pre>";
相关问题