/    Sign up×
Community /Pin to ProfileBookmark

‘Query’ an array?

Hi,
I have a multidimensional array which contains all the rows from a table.

[CODE]
ID | TITLE | SOMETHING ELSE | ETC
[/CODE]

I have another variable containing an integer which refers to the ID in the table. I want to get the corresponding row from the multidimensional array, rather than unnecessarily querying the database again.

So basically, is there a way to perform this?

SELECT * FROM the array WHERE ID = $id

Any advice appreciated.

Thanks

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogAug 07.2009 — You could do a foreach() loop on the array until you find a sub-array with the desired value for the ID.
[code=php]
function queryArray($array, $idName, $idValue)
{
foreach($array as $row)
{
if($row[$idName] == $idValue)
{
return $row;
}
}
return false; // no match found
}
// USAGE:
$rowYouWant = queryArray($resultSet, 'ID', $id);
[/code]


A more efficient method would be to create the array in the first place with the first array index being the ID, e.g.:
[code=php]
$resultSet = array();
while($row = mysql_fetch_assoc($result))
{
$resultSet[$row['ID']] = $row;
}
[/code]

Then in this example, to access a given result row you would simply grab $resultSet[$id].
×

Success!

Help @JitsuDan spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...