将数组中的值与另一个数组的值匹配,并将新数组中的相应值作为循环返回

时间:2014-03-20 11:41:01

标签: php arrays

我无法找到解决以下问题的方法。

我需要获取一个数组的第一个值($split),在另一个数组($array)中找到它并将相应的值返回到一个新数组($matched),然后循环,直到$split中的所有值都匹配并返回(按顺序)到$matched

我已在下面注释了我的代码,以便进一步解释。

<?php

$split = explode('/', '1/2/3');

// $split can be any length and any order

// EG. $split = explode('/', '1/2/3/66/4/9'); 

$result = $connection->query("SELECT id, filename FROM pages");

while ($row = $result->fetch_array()) {
    $new_array[$row['id']] = $row;
}

foreach($new_array as $array) {       

    // take first value from $split
    // match value with 'id' of $array
    // return corresponding 'filename'
    // set as first value of $matched

    $matched = // 

    // loop until all values from $split have been matched
    // and the corresponding filename has been added to $matched.

}

$join = implode('/', $matched); // join $matched as string.

?>

3 个答案:

答案 0 :(得分:1)

尝试以下示例:

    // ... some code
    $matched = array();
    foreach ( $split AS $key ) {
        if ( isset($array[$key]) ) {
            $matched[] = $array[$key];
        }
    }
    return $matched;
    // ... more code

答案 1 :(得分:1)

Let'see:

  • 您有数字列表(ID),
  • 你有地图:id - &gt;文件名
  • 你需要文件名(斜线破坏)

这样:

<?php

// $split can be any length and any order
// EG. $split = explode('/', '1/2/3/66/4/9'); 
$split = explode('/', '1/2/3');

// NB!
$split = array_flip( $split );

$result = $connection->query("SELECT id, filename FROM pages");

/* I need exactly map id -> filename for implode() */
while ($row = $result->fetch_assoc()) {
    $new_array[$row['id']] = $row['filename'];
}

$matched = array_intersect_key($new_array, $split);

$join = implode('/', $matched); // join $matched as string.

?>

答案 2 :(得分:1)

我会用这种方式构建一个mysql查询:

SELECT id, filename FROM pages WHERE id IN(1,2,3,66,4,9) ORDER BY FIELD(id,1,2,3,66,4,9)

然后,在php:

while($row = $result->fetch_assoc()) {
   $match[] = $row;
}
相关问题