PHP - 为数组中的一个键分配两个值

时间:2013-12-21 13:06:01

标签: php arrays loops key

我需要以这种格式获得一个数组:

$arr = {

$domain => $PR => $OBL

}

换句话说,我希望每个域都充当一个键,它有两个值,PR和OBL(pagerank和出站链接)分配给它。只为一个值执行此操作很简单,我只需循环并设置:$arr[$domain] = $PR;

然后通过简单的for-each循环轻松提取数据。但是,为每个域存储两个值的最佳方法是什么?如何循环它以便稍后提取数据?

2 个答案:

答案 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);