将键添加到多个数组中,并用另一个有序数组中的相应值依次填充该键的值


Adding key to multiple arrays and filling the values for that key in order with the corresponding value from another ordered array

我有一些代码(下面)获取两个数组,一个以逗号分隔的用户声明产品的列表和一个相应的以逗号分隔的用户声明产品的时间列表。然后,它将user_id与users表进行匹配,并在多个数组中获取用户信息。我想在每个输出数组中附加相应的claimed_time,但不知道该怎么做。

    $q = "SELECT claimed_by, claimed_time FROM post WHERE post_id='$post_id' AND accepted_user='' AND user_id='$id'";
    $r = mysqli_query ($dbc, $q) or trigger_error("Query: $q'n<br />MySQL Error: " . mysqli_error($dbc));
    if (mysqli_num_rows($r) == 1) {
                $postrow = mysqli_fetch_array($r,MYSQLI_ASSOC);
                $arr = explode(',', $postrow['claimed_by']);
                $arr2 = explode(',', $postrow['claimed_time']);
$users = array();
$r = mysqli_query($dbc,"SELECT * FROM users
WHERE id in (".implode(',',$arr).")");
$count=0;
 while($row = $r->fetch_assoc()){
    $multiple_row_result[] = $row;  
}

echo json_encode($multiple_row_result);//result

我试着将以下代码放入while循环中,但没有成功:

$multiple_row_result['claimed_time']=$arr2

我在想类似foreach语句的东西可能会起作用,但是不能让任何东西起作用。

谢谢。

如果您重新构建您的表结构,将更容易做到这一点。

但是在你当前的格式中,你可以这样写

while($row = $r->fetch_assoc()){
    //get the key from the id array - $arr
    $key = array_search($row['id'], $arr);
   //get the claimed_time for the id using the $key and add to $row
   $row['claimed_time'] = $arr2[$key];
    $multiple_row_result[] = $row;  
}