MorningSleeper
MorningSleeper

Reputation: 415

How to return item from multi dimensional array?

I have a text file with contents such as following which are ids and names.

23414,apple
24323,orange
64563,banana

In a PHP file I read in the content of the text file into an array like

$itemArray = array();

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

If I know the id of a particular record say 24323, how can I return the associated name, orange. All ids are unique. I tried something like the following with no luck.

$id = 24323;

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

Edit: To clarify code.

Upvotes: 1

Views: 58

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short preg_match_all + array_combine functions solution:

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]);

The output:

orange

Upvotes: 0

Orcl_man
Orcl_man

Reputation: 51

I think the problem is this, when the text file was read, exploded and pushed into array, each was treated as an individual element of the array which results in array structure like:

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

So I think you should read with index

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

If I know the id of a particular record say 2, how can I return the associated name, orange. All ids are unique. I tried something like the following with no luck.

Since you said ids are unique, better you create array like below,

$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];  
   */
}

and you can access them easily like below

$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

Upvotes: 2

Related Questions