向数组添加另一个维度

时间:2015-07-28 04:51:06

标签: php arrays multidimensional-array

我有一系列顶级域名和价格,现在我希望能够在域名中添加“澳大利亚”,“新西兰”,“行业”等分类,但我在添加额外维度方面遇到了麻烦。 / p>

我拥有的数组是

$domains = array(
'.com.au' => '19.98', 
'.melbourne' => '90.00', 
'.academy' => '45.00', 
'.accountants' => '120.00', 
'.ac.nz' => '36.75');

2 个答案:

答案 0 :(得分:0)

$domains = array(
'.com.au' => array(
'country' => 'Australia',
'sector' => 'Industry',
'price' => '19.98'
), 
);

这是你正在寻找的开始吗?

答案 1 :(得分:0)

这段代码对你好吗?

<?php
$domains = array(
'.com.au' => '19.98', 
'.melbourne' => '90.00', 
'.academy' => '45.00', 
'.accountants' => '120.00', 
'.ac.nz' => '36.75');

$newDomains = [];
foreach($domains as $key=>$value){
    if($key == '.com.au'){
        $newDomains[$key]['TLD'] = $value;
        $newDomains[$key]['Industry'] = 'blabal';
    }else{
        $newDomains[$key] = $value;
    }
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
?>

甚至:

$domains = array(
'.com.au' => '19.98', 
'.melbourne' => '90.00', 
'.academy' => '45.00', 
'.accountants' => '120.00', 
'.ac.nz' => '36.75');


$industryArray = array(
    '.com.au' => 'blabla'
    );


$newDomains = [];
foreach($domains as $key=>$value){

    if(isset($industryArray[$key])){
        $newDomains[$key]['TLD'] = $value;
        $newDomains[$key]['Industry'] = $industryArray[$key];
    }else{
        $newDomains[$key] = $value;
    }
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';

结果是:

array(5) {
  [".com.au"]=>
  array(2) {
    ["TLD"]=>
    string(5) "19.98"
    ["Industry"]=>
    string(6) "blabla"
  }
  [".melbourne"]=>
  string(5) "90.00"
  [".academy"]=>
  string(5) "45.00"
  [".accountants"]=>
  string(6) "120.00"
  [".ac.nz"]=>
  string(5) "36.75"
}