【问题标题】:Adding key to multiple arrays and filling the values for that key in order with the corresponding value from another ordered array将键添加到多个数组并使用另一个有序数组中的相应值按顺序填充该键的值
【发布时间】:2014-08-09 11:39:41
【问题描述】:

我有一些代码(如下),它获取两个数组,一个以逗号分隔的已声明产品的用户列表和一个相应的以逗号分隔的用户声明时间列表。然后它将 user_id 与 users 表匹配,并在多个数组中获取用户信息。我想将相应的 claim_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 语句的东西可能会起作用,但不能让任何东西起作用。

谢谢。

【问题讨论】:

    标签: php arrays foreach while-loop


    【解决方案1】:

    如果您重新构建表结构,这样做会更容易。

    但是在您当前的格式中,您可以执行类似的操作

    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;  
    }
    

    【讨论】:

    猜你喜欢
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2018-01-24
    相关资源
    最近更新 更多