如何使用PHP中的索引位置访问值关联数组

时间:2011-12-06 05:25:08

标签: php arrays

使用关联数组,例如:

$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");

我尝试使用以下方法访问某个值:

$fruits[2];

这给了我一个PHP notcie:Undefined offset;

有办法吗?

由于

2 个答案:

答案 0 :(得分:7)

如果您想将其保留为关联数组,则不会。如果要使用数字键索引,可以执行以下操作:

$fruits  = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
$fruits2 = array_values($fruits);

echo $fruits2[2];

在PHP手册中了解有关array_values()的更多信息。


更新:比较你在评论中提到的两个关联数组,你可以这样做(如果他们有相同的键 - 如果不是,你应该添加isset()检查):

foreach (array_keys($arr1) as $key) {
  if ($arr1[$key] == $arr2[$key]) {
    echo '$arr1 and $arr2 have the same value for ' . $key;
  }
}

或者,为了避免使用array_keys函数调用:

foreach ($arr1 as $key => $val) {
  if ($val == $arr2[$key]) {
    echo '$arr1 and $arr2 have the same value for ' . $key;
  }
}

答案 1 :(得分:1)

这是另一个想法。如果没有关于您的最终目标或更大项目的更直接信息,我就无法与任何具体实施进行对话。

<?php
$fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry');
$flavors = array( 'a' => 'crisp', 'b' => 'mushy', 'c' => 'tart' );

reset($fruit);
reset($flavors);

while (list($key, $val) = each($fruit))
{
    list( $flavorKey, $attribute ) = each( $flavors );

    echo "{$key} => {$val}<br>\n";
    echo "{$attribute}<br><br>\n";
}

[根据对array_count_values的评论编辑]

<?

$words = explode( " ", 'the quick brown fox jumped over the lazy yellow dog' );
$words2 = explode( " ", 'the fast fox jumped over the yellow river' );
$counts = array_count_values( $words );
$counts2 = array_count_values( $words2 );

foreach( $counts as $word => $count )
{
    if ( array_key_exists( $word, $counts2 ) && $counts2[$word] == $counts[$word] )
    {
        echo $word . ' matched.<br>';
    }
}
相关问题