Jump to content

select a row from array


samtwilliams

Recommended Posts

then why didn't you say you wanted each element rather than just selecting a specified 'row'?

 

you could use

<?php
$selectedRow = $array[2];
list($patientid, $forename, $surname], $dob) = $selectedRow;

?>

[i don't like list() but thats just me...

or

 

<?php
$selectedRow = $array[2];
foreach( $selectedRow as $key => $val)
{
    $$key = $val;
}
?>

The latter will produce variables of whatever your array indexes are called (provided they are not numeric - in which case it will fail miserably) so is in that sense a bit more robust.

 

 

 

array_search

 

This code snippet came from a user comments:

function recursiveArraySearch($haystack, $needle, $index = null) 
{ 
    $aIt     = new RecursiveArrayIterator($haystack); 
    $it    = new RecursiveIteratorIterator($aIt); 
    
    while($it->valid()) 
    {        
        if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($it->current() == $needle)) { 
            return $aIt->key(); 
        } 
        
        $it->next(); 
    } 
    
    return false; 
} 

 

To use with your situation (given that you define the function in your code:

$rowIndex = recursiveArraySearch($array, '2', 'patientid');
print_r($array[$rowIndex]);

 

Side note:

I have no clue where toon was going at, but yea. I think he missed the point.

It just states 'Array'

 

Well, duh! You said it was a multi-dimensional array and you wanted to select a row, i.e. one of the sub arrays. Be a little more specific in your requests and then there woul dbe no need for this post to require 6+ replies!

 

Well, there is always extract():

 

$index = 2;
extract($array[$index]);
echo "Patient ID: {$patientid}<br />\n";
echo "Forename: {$forename}<br />\n";
echo "Surname: {$surname}<br />\n";
echo "DOB: {$dob}<br />\n";

 

Output:

Patient ID: 2
Forename: Samue
Surname: Williams
DOB: 17/08/1985

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.