(PHP)如何使用与变量相关的字符串来命令多维数组?

(PHP)如何使用与变量相关的字符串来命令多维数组?

问题描述:

Hey I have a new feature on my website where you can search for ya items by entering some keywords in the search input. Of course I am using ajax and I need a new function which sort or order the array which holds the item info from the database related to the keyword which the user writes in the input field. When the user hits for example "m" so it should be displayed in this way.

array [["836","123","Malaga - Ocean","1"],
       ["834","123","Malaga City","1"],
       ["838","123","DayZ - Novo Turm #1","0"],
       ["839","123","DayZ - Novo Turm #2","0"],
       ["840","123","DayZ - Novo Turm #3","0"]]

But if Im searching for something which begins with the letter "m", "Malaga City" and "Malaga - Ocean" should be displayed first in the result.

I am searching more then one table for the keyword where I collect it. But if I am adding the array in every different table results I get so every time the picture table results first.

MySql:

$sql_picture = "SELECT * FROM pictures [...] ORDER BY name LIMIT 5";
$sql_videos = "SELECT * FROM videos [...] ORDER BY name LIMIT 5";
$sql_audio = "SELECT * FROM audio [...] ORDER BY name LIMIT 5";
$sql_documents = "SELECT * FROM documents [...] ORDER BY name LIMIT 5";

PHP:

$collectedDataName = array();

for($i = 0; $i < count($collectData); $i++){
    $collectedDataName[$i] = $collectData[$i][2];
}

$collectData_lowercase = array_map('strtolower', $collectedDataName);

array_multisort($collectData_lowercase, SORT_ASC, SORT_STRING, $collectedDataName);

$returnData = array();

for($j = 0; $j < 5; $j++){
    for($i = 0; $i < count($collectData); $i++){
        if($collectData[$i][2] === $collectedDataName[$j]){
            $returnData[$j] = $collectData[$i];
        }
    }
}

echo json_encode($returnData);

Result:

array [["838","123","DayZ - Novo Turm #1","0"],
      ["839","123","DayZ - Novo Turm #2","0"],
      ["840","123","DayZ - Novo Turm #3","0"],
      ["836","123","Malaga - Ocean","1"],
      ["834","123","Malaga City","1"]]

How can I sort my multi dimensonal array by its string value related to a variable?

You want to sort your multi dimensional array based on the input value, a little bit like we do in sql using

select * from table where column like 'inputValue%'

This is a solution based on php only

$inputvalue = 'm';
$inputvalue = strtolower($inputvalue);

$collectData = [["838","123","DayZ - Novo Turm #1","0"],
             ["834","123","Malaga City","1"],
             ["839","123","DayZ - Novo Turm #2","0"],         
             ["836","123","Malaga - Ocean","1"],
             ["840","123","DayZ - Novo Turm #3","0"],
            ];

/*
we use strpos to check if the input value is contained in the strings array, if not we use levenshtein to calculate the distance between them.*/

$distances = array();
$positions = array();
for ($i=0; $i < count($collectData); $i++) {    
  $current_val = strtolower($collectData[$i][2]);
  if (strpos($current_val, $inputvalue)!==false)
    $distance = strpos($current_val, $inputvalue);
  else
    $distance = levenshtein($inputvalue, $current_val);

  $distances[] = $distance;        
  $positions[] = array("distance"=>$distance, "position"=>$i);        
}

/*we sort distances*/
sort($distances);

/* we reorder collectData based on distances sort  */
$returnData = array();
for ($j=0; $j<count($distances); $j++) {
  for ($k=0; $k<count($positions); $k++) {
    $val = $collectData[$positions[$k]["position"]];

    if ($distances[$j]==$positions[$k]["distance"] && !in_array($val, $returnData)) {
        $returnData[] = $val;
        break;
    }
  }
}

return $returnData;

levenshtein php doc here : levenshtein function

Could array_multisort Help? Are you meant to be returning results that only begin with "m"?

<?php
// create an array of the "column" to sort on...
foreach ($returnData as $row)  
{
    $test[] = $row[2];
}

// sort it...
array_multisort($test, SORT_DESC, $returnData);
?>

There are two potential solutions to your problem:

1. SQL Solution

Have the database do the sorting for you by using a union. For example:

SELECT
   id1, 
   id2,
   name
FROM
   (
       (SELECT id1, id2, name FROM pictures WHERE something=... ORDER BY name LIMIT 5)
       UNION ALL
       (SELECT id1, id2, name FROM videos WHERE something=... ORDER BY name LIMIT 5)
    ) AS q
ORDER BY
   name

2. PHP Solution

You are doing a non-standard sort, so you need to use usort which takes a comparator function that compares two array items:

$allData = array_merge($sql_picture, $sql_video, ...);
usort($allData, function($a, $b) { return strcmp($a[2], $b[2]); });