将键添加到数组

时间:2015-09-17 09:05:03

标签: php arrays dom

array { [0]=>
 City
 Street
 Zip

我有这个,但我需要的是:

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

我正在使用PHPDOM来获取我添加到数组中的html

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

我正在使用DOM处理的HTML部分

 <div class="contentSection">

    City
    <br>
    Street
    <br>
    ZIP                

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

    City
    <br>
    Street
    <br>
    ZIP 

我试图做的事情是

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

    ?>

但这会返回:

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

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

第二部分出错了

2 个答案:

答案 0 :(得分:0)

你可以这样做 您需要重新创建关联数组。

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

答案 1 :(得分:0)

试试这个:

$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('div') as $element) {
    if (strpos($element->getAttribute('class'), 'contentSection') !== false) {
        $string = $element->C14N();
    }
}
$array = explode('<br>',explode("</p>", $string));
foreach($array as $arr){
    $v = trim(strip_tags($arr)); //remove html tags
    $out[$v] = $v; 
}
print_r($out);