添加关键数组 [英] Add Keys to array
本文介绍了添加关键数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
array { [0]=>
City
Street
Zip
我有这个,但我需要的是这样的:
I have this but what I need is something like:
array { [0]=>
'city'=>City
'Street'=>Street
'zip'=>Zip
我使用PHPDOM得到的HTML,我不是增加一个阵列
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部分,我用DOM处理
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;
}
?>
但这返回:
Array ( [city] =>
city[street] =>
street [zip] =>
zip
city [3] =>
street [4] =>
zip
因此,在第二部分中出错
So it goes wrong in the second part
推荐答案
试试这个,
foreach($array as $value){
$data[$value] = $value;
}
print_r($data);
可能是您解决问题。
May be solve your problem.
这篇关于添加关键数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文