简体   繁体   English

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

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

I have some code (below) that gets two arrays, a comma separated list of users that have claimed a product and a corresponding comma separated list of when they claimed it. 我有一些代码(下),该代码获得两个数组,一个声明产品的用户的逗号分隔列表,以及一个声明产品时的相应逗号分隔列表。 It then matches the user_id to the users table and gets the user info in multiple arrays. 然后将user_id与users表匹配,并以多个数组获取用户信息。 I want to append the corresponding claimed_time into each of the outputted arrays, but can't figure out how to do it. 我想将相应的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

I've tried putting the following into the while loop with no success: 我尝试将以下内容放入while循环中,但未成功:

$multiple_row_result['claimed_time']=$arr2

I was thinking something along the lines of a foreach statement might work, but can't get anything to work. 我在想像foreach语句一样的东西可能有用,但是什么也没用。

Thanks. 谢谢。

It would be easier to do this if you restructured your table structure. 如果您重组表结构,这样做会更容易。

But in your current format, you could do something like 但是以您当前的格式,您可以执行以下操作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM