duanbiyi7319 2015-09-17 09:05 采纳率: 100%
浏览 59

将键添加到数组

array { [0]=>
 City
 Street
 Zip

I have this but what I need is something like:

array { [0]=> 
 'city'=>City
 'Street'=>Street
 'zip'=>Zip

I am using PHPDOM to get the html which I than add to an array

$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('div') as $element) {
    if (strpos($element->getAttribute('class'), 'contentSection') !== false) {
        $string = $element->C14N();
    }
}

$array = explode("</p>", $string);
print_r($array);

HTML part that I am processing with DOM

 <div class="contentSection">

    City
    <br>
    Street
    <br>
    ZIP                

    <p class="Separator">
    </p>

    City
    <br>
    Street
    <br>
    ZIP 

Something that I tried to do is

  $dom = new DOMDocument('1.0');
    $dom->loadHTML($html);
    foreach ($dom->getElementsByTagName('div') as $element) {
        if (strpos($element->getAttribute('class'), 'contentSection') !== false) {
            $string = $element->C14N();
        }
    }

        $keys = array("city","street", "zip");
$array = array_explode_with_keys("<br>", $keys, $string);
        print_r($array);

    function array_explode_with_keys($delimiter, $keys, $string){
        $return = array();
        $pieces = explode($delimiter,$string);
        foreach($pieces as $i=>$piece){
            if($i<count($keys)) {
                $return[$keys[$i]] = $piece;
            } else {
                $return[$i] = $piece;
            }
        }
        return $return;
    }

    ?>

but this returns:

Array ( [city] =>
city[street] =>
street [zip] =>
zip

city [3] =>
street [4] =>
zip

So it goes wrong in the second part

  • 写回答

3条回答 默认 最新

  • doujiao1180 2015-09-17 09:09
    关注

    You can do like this You need to recreate an associative array.

    $dom->loadHTML($html);
    foreach ($dom->getElementsByTagName('div') as $element) {
        if (strpos($element->getAttribute('class'), 'contentSection') !== false) {
            $string = $element->C14N();
        }
    }
    
    $array = explode("</p>", $string);
    foreach($array as $arr){
        $array[$arr] = $arr; //Adding Keys to array same as value of array
    }
    print_r($array);
    
    评论

报告相同问题?