2010-11-30 87 views
1

是否可以定義一個可以通過字符串和數字索引訪問元素的數組?使用關聯索引和編號索引訪問數組元素

+0

我覺得這是你在說什麼。像這樣創建一個數組:`array('a'=>'x','b'=>'y','c'=>'z')`,並用'$ array [ 1]`(因爲它是第二個索引)。是對的嗎? – Jonah 2010-11-30 16:57:12

回答

3

你可以這樣做。

$arr = array(1 => 'Numerical', 'two' => 'string'); 
echo $arr[1]; //Numerical 
echo $arr['two']; //String 
+0

甚至沒有接近正確的答案。您正在打印兩個具有不同類型索引的不同元素。 – roger 2010-11-30 17:07:10

3

PHP允許字符串和數字索引元素的混合。

$array = array(0=>'hello','abc'=>'world'); 

echo $array[0]; // returns 'hello' 
echo $array['0']; // returns 'hello' 
echo $array['abc']; // returns 'world'; 
echo $array[1]; // triggers a PHP notice: undefined offset 

在最後一個項目$array[1]一仔細觀察就會發現,它不等同於數組的第二個元素。

7

array_values()將返回一個數組中的所有值,並將其索引替換爲數字索引。

http://php.net/array-values

$x = array(
    'a' => 'x', 
    'b' => 'y' 
); 
$x2 = array_values($x); 

echo $x['a']; // 'x' 
echo $x2[0]; // 'x' 

另一種方法是構建一套副參照索引。

function buildReferences(& $array) { 
    $references = array(); 
    foreach ($array as $key => $value) { 
     $references[] =& $array[$key]; 
    } 
    $array = array_merge($references, $array); 
} 

$array = array(
    'x' => 'y', 
    'z' => 'a' 
); 

buildReferences($array); 

需要注意的是,如果你不添加或移除指標規劃,這裏只完成。雖然你可以編輯它們。

3

martswite的答案是正確的,但如果你已經有一個關聯數組,它可能無法解決你的問題。以下是一個醜陋的黑客解決此 - 並且應該不惜一切代價避免:

$a = array(
'first' => 1, 
'second' => 2, 
'third' => 3 
); 
$b=array_values($a); 

print $b[2];