如何从多维数组中返回项目?

时间:2017-09-06 04:36:29

标签: php arrays

我有一个文本文件,其中包含以下内容,如ids和名称。

23414,apple
24323,orange
64563,banana

在PHP文件中,我将文本文件的内容读入类似

的数组中
$itemArray = array();

$records = file('/path/to.file/guilds.txt');
foreach ($records as $line) {
$lineArray = explode(',',$line);
array_push($itemArray,$lineArray);  
}

如果我知道特定记录的id为24323,我该如何返回相关名称orange。所有ID都是独一无二的。我尝试过类似下面的东西而没有运气。

$id = 24323;

echo "Result:" . array_search($id, array_column($itemArray,1,0));

编辑:澄清代码。

3 个答案:

答案 0 :(得分:2)

  

如果我知道特定记录的id说2,我怎么能返回   相关名称,橙色。所有ID都是独一无二的。我试过类似的东西   以下没有运气。

由于您说ids是唯一的,因此您可以更好地创建如下所示的数组

$itemArray = array();

$records = file('/path/to.file/guilds.txt');
foreach ($records as $line) 
{
    $lineArray = explode(',',$line);
    $itemArray[ $lineArray[0] ] = $lineArray;  

   /* Use below if you just want to store name 
      $itemArray[ $lineArray[0] ] = $lineArray[0];  
   */
}

您可以轻松访问它们,如下所示

$id = 24323;
print_r( $itemArray[$id] );

/*You will get below
          Array
          (
            [0] => 24323
            [1] => orange
           )

*/

// and if you want just to print orange then
echo $itemArray[$id][1];   // orange

答案 1 :(得分:0)

我认为问题是这样的,当文本文件被读取,爆炸并推入数组时,每个被视为数组的单个元素,这导致数组结构如下:

$itemArray[0] => 1
$itemArray[1] => Apple
$itemArray[2] => 2
$itemArray[3] => Orange
$itemArray[4] => 3
$itemArray[5] => banana

所以我认为你应该阅读索引

答案 2 :(得分:0)

preg_match_all + array_combine个功能解决方案:

preg_match_all('/^(?P<id>[0-9]+),(?P<name>\w+)\s*/m', file_get_contents('/path/to.file/guilds.txt'), $m);
$result = array_combine($m['id'], $m['name']);

print_r($result[24323]);

输出:

orange