-5

ちょっと私は配列を持っています。各値を区切る必要があるので、次のようになります

$arry = array(a,b,c,d,e,f)
$point1 = (SELECT distance FROM Table WHERE Origin = a AND Destination = b);
$point2 = (SELECT distance FROM Table WHERE Origin = b AND Destination = c);
$point3 = (SELECT distance FROM Table WHERE Origin = c AND Destination = d);
$point4 = (SELECT distance FROM Table WHERE Origin = d AND Destination = e);
$point5 = (SELECT distance FROM Table WHERE Origin = e AND Destination = f);
$point6 = (SELECT distance FROM Table WHERE Origin = f AND Destination = g);
$point7 = (SELECT distance FROM Table WHERE Origin = g AND Destination = f);

$total_trav = $point1+$point2+$point3+$point4+$point5+$point6+$point7
4

3 に答える 3

2

シンプルに list(); を使用します。

list($point1,$point2,$point3,$point4,$point5) = $arry;

次に、クエリを次のように実行します....

$sql = "SELECT SUM(distance) FROM table WHERE (origin='$point1' AND destination='$point2') OR (origin='$point2' AND destination='$point3') OR (origin='$point3' AND destination='$point4') OR (origin='$point4' AND destination='$point5')

編集

以下のコメントで必要なものに基づいて、簡単な解決策を考えました....

$arr = array("Vegas","Iowa","Utah","Washington"); //your array

//First part of query string build... 
$sql = "SELECT SUM(distance) FROM table WHERE";

//Loop through the array...based on its # of contents
for($i=0;$i<count($arr);$i++){
   if(!empty($arr[$i+1])){
   $sql.=" (origin='".$arr[$i]."' AND destination='".$arr[$i+1]."') OR";}
 }
  //Hack off the end bit, which contains an OR appended to the string...
  $sql = substr($sql, 0, -3);

  //$sql is now ready to be used in a query
  mysql_query($sql); 
于 2013-06-26T02:41:04.160 に答える
1

使用するextract

キーを名前として使用して、配列から変数に要素を抽出します。

于 2013-06-26T02:40:56.760 に答える
1

これはすべて SQL で行うことができます。

SELECT SUM(distance) 
FROM table 
WHERE (origin='a' AND destination='b') 
   OR (origin='b' AND destination='c')
   OR (origin='c' AND destination='d')

など。

于 2013-06-26T02:42:49.473 に答える