FUDforum
Fast Uncompromising Discussions. FUDforum will get your users talking.

Home » Imported messages » comp.lang.php » Fast/Easy way to extract a column from multi-dimensional array?
Show: Today's Messages :: Polls :: Message Navigator
Return to the default flat view Create a new topic Submit Reply
Re: Fast/Easy way to extract a column from multi-dimensional array? [message #176834 is a reply to message #176833] Fri, 27 January 2012 21:42 Go to previous messageGo to previous message
Thomas 'PointedEars'  is currently offline  Thomas 'PointedEars'
Messages: 701
Registered: October 2010
Karma:
Senior Member
Thomas Mlynarczyk wrote:

> John Drako schrieb:
>> I'm looking for a way to get all the values from the column of a two
>> dimensional array.
>
>> RecordID, name, last name, title
>> RecordID, name, last name, title
>> RecordID, name, last name, title
>> RecordID, name, last name, title
>> RecordID, name, last name, title
>> RecordID, name, last name, title
>> etc...
>>
>> I need to get all the 'RecordID' from the results to reuse in other
>> queries.
>
> If it's the first column you're interested in:
>
> array_map( 'current', $array )

array_map() it is, but one should not rely on that the array cursor is at
the first element. Since the OP is passing MYSQLI_ASSOC, they should use

$recordIds = array_map(
create_function('$e', 'return $e["RecordID"]'),
$arr
);

for one-time use or

public static function getRecordId($result)
{
return $result['RecordID'];
}

public function getResults()
{
$arr = …;

$recordIds = array_map(array('self', 'getRecordId'), $arr);
}

in a class. Adjust visibility to the necessary minimum.

However, it is better to map the result of a database query to model objects
(cf. MVC pattern):

public function getResults()
{
$arr = …;

foreach ($arr as $row)
{
$results[] = new Result($row);
}

return $results;
}

The (example) `Result' constructor would then cause the elements of the
array to be mapped, according to their key, to properties of `Result'
instances, allowing for implicit range checking and type conversion through
setters (preferably the __set() magic method calling them on access of non-
public properties from public context).


PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
[Message index]
 
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Read Message
Previous Topic: approaches to PHP-based application interface?
Next Topic: php+html mixup in displaying multidimensional array in html tables
Goto Forum:
  

-=] Back to Top [=-
[ Syndicate this forum (XML) ] [ RSS ]

Current Time: Thu Nov 28 02:41:19 GMT 2024

Total time taken to generate the page: 0.04981 seconds