0

I am trying to push values onto an array like so:

$scoreValues[$i][] = $percent ;
$scoreValues[$i][] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;

I basically want to link together the $percent with the string, so I get an output like:

array (0 > array('46.5', '<span etc etc')

I then plan to sort by the percent sub-array so I have the highest scoring strings at the top.

imperium2335
  • 20,168
  • 36
  • 103
  • 181
  • possible duplicate of [How do I sort a multidimensional array in php](http://stackoverflow.com/q/96759/), [how to create a multidimensional array PHP](http://stackoverflow.com/q/8638051/) – outis Jul 17 '12 at 09:01

3 Answers3

1

In the second line you need to specify the index of the second array:

$scoreValues[$i][$j] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;

So you basically need 2 counters, one for the external array ($i) and on for the internal array ($j).

EDIT:

You got me a bit confused with the question, seems like what you need is not a multi dimensinal array but rather a simple array:

$scoreValues[$percent] = '<span id="item'.$i.'" class="suggestElement" data-entityid="'.$row['id'].'" data-match="'.$percent.'">'.rawurldecode($row['name']).'</span>' ;

Please note that this requires $percent to be unique.

Tomer
  • 16,381
  • 13
  • 64
  • 124
1

Simplest way would be to use two arrays :

$percents[$i] = $percent;
$scores[$i] = "<span....>");

Or one array, but indexed like this

$data = new arrray('percents' => array(), 'scores' => array());
$data['percents'][$i] = $percent;
$data['scores'][$i] = "<span....>");

Once this is done, you then sort your arrays using array_multisort :

array_multisort(
   $data['percents'], SORT_DESC,
   $data['scores']);
Ugo Méda
  • 1,194
  • 6
  • 22
0

Try this:

$val = array(
    'percent' => $percent,
    'html' => '<span id="item' . $i .
              '" class="suggestElement" data-entityid="'.$row['id'].
              '" data-match="'.$percent.'">'.rawurldecode($row['name']).
              '</span>'
);
// This just pushes it onto the end of the array
$scoreValues[] = $val ;
// Or you can insert it at an explicit location
//$scoreValues[$i] = $val;
halfer
  • 18,701
  • 13
  • 79
  • 158