我需要以这种格式获得一个数组:
$arr = {
$domain => $PR => $OBL
}
换句话说,我希望每个域都充当一个键,它有两个值,PR和OBL(pagerank和出站链接)分配给它。只为一个值执行此操作很简单,我只需循环并设置:$arr[$domain] = $PR;
然后通过简单的for-each循环轻松提取数据。但是,为每个域存储两个值的最佳方法是什么?如何循环它以便稍后提取数据?
答案 0 :(得分:6)
假设您正在运行最新的PHP(5.5.x):
$arr = [
'domain1.tld' => [8, 2543],
'domain2.tld' => [3, 684],
];
foreach($arr as $domain => list($pr, $obl))
echo "<p>$domain has PageRank $pr and $obl outbound link(s)</p>";
或者,更兼容,更详细:
$arr = [
'domain1.tld' => ['PR' => 8, 'OBL' => 2543],
'domain2.tld' => ['PR' => 3, 'OBL' => 684],
];
foreach($arr as $domain => $properties) {
$pr = $properties['PR'];
$obl = $properties['OBL'];
echo "<p>$domain has PageRank $pr and $obl outbound link(s)</p>";
}
答案 1 :(得分:2)
添加到Niels Keurentjes`回答:
$arr = array(
'domain1.tld' => array(8, 2543),
'domain2.tld' => array(3, 684),
);
array_map(
function ($domain,$values){
list($pr, $obl) = $values;
echo "<p>$domain has PageRank $pr and $obl outbound link(s)</p>";
}
,array_keys($arr)
,$arr);