1

我正在尝试检查数组中是否存在一个值,如果存在,它应该从数据库中回显有关该值的信息。

我现在得到的是“空”结果,但我希望在列表中至少得到三个结果,它们同时存在于数组和数据库中。

这是数组的 var_dump 外观,它不是整个数组,但它仍然看起来相同:$friends = array($friends['data']);

array(1) {
[0]=>
array(680) {
[0]=>
array(2) {
  ["name"]=>
  string(17) "One friends name"
  ["id"]=>
  string(8) "FRIEND_ID"
}
[1]=>
array(2) {
  ["name"]=>
  string(13) "Another friends name"
  ["id"]=>
  string(9) "FRIEND_ID"
}
[2]=>
array(2) {
  ["name"]=>
  string(22) "Another friends name"
  ["id"]=>
  string(9) "FRIEND_ID"
}

PHP代码:

<?php

$query_top_list_friends = mysql_query("
SELECT * FROM ".$DBprefix."users 
WHERE center_id='" . $personal['center_id'] . "' 
ORDER BY workouts DESC LIMIT 10");

$i = 0;
$friends = array($friends['data']);

while ($top_list_friends = mysql_fetch_array($query_top_list_friends)) 
{
//Below it should only echo if the "fid" in the database and the "id" in the array is equal, then it should echo information based on that id from the database
if($friends[$top_list_friends['fid']])
{
    $i++;
    echo "<div class='user'>";
    echo "<span class='number'>" . $i . "</span>";
    echo "<span class='name'>" . $top_list_friends['name'] . "</span>";
    echo "<span class='workouts'>" . $top_list_friends['workouts'] . "</span>";
    echo "</div>";
} 
}  

有什么想法可以解决这个问题吗?

4

2 回答 2

2

在我看来,它$friends = array($friends['data']);在索引 0 处保存了朋友数组,所以当你打电话时,if($friends[$top_list_friends['fid']])你不是在查看保存朋友的数组,而是保存朋友的数组的数组,如果这有意义的话

尝试更改$friends = array($friends['data']);$friends = $friends['data'];,您应该开始得到结果,但是 fid 是如何工作的?它是指向数组的索引还是数组的键?从您在上面发布的数组中看到,唯一可访问的值是:

$friends[0][0] // One friend
$friends[0][1] // Another friend
$friends[0][2] // Another friend

所以请确保 fid 是一个整数,因为调用$friends[0][$fid]需要是一个 0 到 2 的整数才能返回任何数据

希望有帮助,我很乐意回答任何问题

于 2013-09-23T19:21:13.543 回答
1

您应该能够使用SQL's来实现这一点IN

$array = array(
    array(
        'id' => 5,
        'name' => 'Harry'
    ),
    array(
        'id' => 8,
        'name' => 'Josh'
    )
);

// create an array with just your fid's
$sql_in_values = array_map(function($ele){
    return $ele['id'];
}, $array);

// select all entries where the fid's are specified
$query_top_list_friends = mysql_query("
    SELECT * FROM ".$DBprefix."users 
    WHERE center_id='" . $personal['center_id'] . "'
    AND WHERE fid IN ('" . implode(',', $sql_in_values) . "')
    ORDER BY workouts DESC LIMIT 10");

$i = 0;
while($top_list_friends = mysql_fetch_array($query_top_list_friends)){
    echo "<div class='user'>";
    echo "<span class='number'>" . ++$i . "</span>";
    echo "<span class='name'>" . $top_list_friends['name'] . "</span>";
    echo "<span class='workouts'>" . $top_list_friends['workouts'] . "</span>";
    echo "</div>";
} 
于 2013-09-23T19:34:07.723 回答