1

I'm working on a search system for my database where I break the search phrase into individual search words, search my mySQL database keyword table for any occurrence of those words, and then output a list of IDs associate with the keyword.

I want to add those ID's to a new array that will also contain a count value and (from a new query) the name of the place belonging to the ID, resulting in:

array(ID, count, name)

For each search word I want to go through this process and if the ID is already in the above array I want to increase the count value and if not, I want to add it with a count value of 1.

When the array is built and all the counting is done, I want to sort it by count and then name, and then output the results.

I've programmed PHP for quite some time but I've never been good with building and manipulating arrays so any help related to building, searching, editing, and sorting a 3-column array is appreciated.

Here's some code below where I'm just trying to insert data into the array and spit it out, which obviously doesn't work:

<?php
$id = 5;
$count = 1;
$name = "PlaceName1";

$arrayPlaces = array($id, $count, $name);

echo "5: " . $arrayPlaces[5] . "<br />";
?>
user2246930
  • 49
  • 1
  • 9
  • I'd suggest you to have ID as the key, then on each row check if the row ID is a key of the array ( in other words, already exists ) then increase array[ID][count] by 1. If you were to provide some code I'd be able to go more in-depth – php_nub_qq Jun 22 '13 at 21:57
  • Added a code example, doesn't work – user2246930 Jun 22 '13 at 22:16
  • Oh no, that's not how you do it. This doesn't look like a search fetching algorithm but well .. – php_nub_qq Jun 22 '13 at 22:18
  • I just need help with adding to and searching the array, once I understand them I can make my search algorithm more complex. – user2246930 Jun 22 '13 at 22:20
  • I submitted an answer, have a look. – php_nub_qq Jun 22 '13 at 22:20
  • using your code, you would need to do - `echo "5: " . print_r($arrayPlaces[0]) . "
    ";` - as you are currently setting the 1st key of `$arrayPlaces` (which starts from 0), and you are trying to echo an array, so you need to use `print_r()`.
    – Sean Jun 22 '13 at 22:25

1 Answers1

0
<?php
$id = 5;
$count = 1;
$name = "PlaceName1";

$arrayPlaces = array(
    $id => array(
        'count' => $count,
        'name' => $name
    )
);

echo "5: " . $arrayPlace[5]['name'] . "<br />";
?>
php_nub_qq
  • 12,762
  • 17
  • 59
  • 123
  • Once I fixed the error in the echo line (which was in my original code) this worked great. Can you show how I would sort the array by count or name? – user2246930 Jun 22 '13 at 22:27
  • Check [this](http://stackoverflow.com/questions/96759/how-do-i-sort-a-multidimensional-array-in-php) out – php_nub_qq Jun 22 '13 at 23:15