user761088
user761088

Reputation: 157

Sorting multi dimensional arrays with search criteria

I am working with FLAT FILE database.

OK. Just to eliminate all the "why not use SQL". i HAVE. This is a personal(learning) project. I like working with text files and want to tinker.

So for 2+ days I've searched google and S.O. and tried many variations of methods presented. However they do not get what I am needing. But I did learn the right question to ask :-)

Now< in SQL you can do it this way (since sql is basically a fancy array)

SELECT * FROM [tablename] WHERE `some_field`='user_input1' ORDER BY `sequence_opt`;

I want to do that in a database of over 2000 records. (they have been serialized for ease of storing in a text file)

currently I did this: ($data_lib is 2000+ records with 30 fields each, but retrieved as

$data_lib[1]['a_field_name1']
$data_lib[2]['a_field_name2']
$data_lib[3]['a_field_name3']
$data_lib[4]['a_field_name etc...'])


 foreach($data_lib as $linenum=>$row)
            $sort[$linenum] = $row['some_field'];
            array_multisort($sort,SORT_DESC,$data_lib);

that is equivalent to SELECT * FROM [tablename] ORDER BY `some_field'

Works perfect. What I can't seem to do it get this to "WHERE" bY selecting another field as a criteria. As in the first SELECT example. I can't get the "WHERE" clause to work.

Now one thing I have not looked at, is the original way I am reading the database - do you think the issue is there? I have tried usort, but I seem to mess the fields doing it that way and the order is wrong.

This site has been absolutely wonderful with all its info, and my questions are perfectly answered.

thank you in advance!!!

Upvotes: 3

Views: 114

Answers (1)

deceze
deceze

Reputation: 522110

Something like this should do:

$results = array_filter($records, function ($row) {
     return $row['some_field'] == 'user input';
});
usort($results, function ($a, $b) {
     return $a['sequence_opt'] - $b['sequence_opt'];  // assuming numeric field

     // alternatively something like:
     // return $a['sequence_opt'] == $b['sequence_opt'] ? 0 :
     //        ($a['sequence_opt'] < $b['sequence_opt'] ? -1 : 1);
});

It's really not very efficient though, compared to SQL.

If this still messes up for you, please specify some more detailed input and expected output.

Upvotes: 1

Related Questions