douyanqu9722 2018-05-07 00:42
浏览 146
已采纳

将带有foreach的数组放在另一个数组中

I've just achieved a code where I make an array with foreach and in the same code I already have an existing array. What I want to do is to make only one array with those two results. Here is my code for the first array :

$sql = "SELECT photoprofile,username from photo WHERE username IN ('somearray')";


$resol = array();
$resulol = mysqli_query($con,$sql);

$photos = mysqli_fetch_all($resulol, MYSQLI_ASSOC);
$photos = array_column($photos, "photoprofile", "username");
foreach ( $restest as $user ) {
  if ( isset($photos[$user])) {
     $res[] = $photos[$user];
 }
 else    {
     $res[] = '';
 };
}

And here is my second array :

while($row = mysqli_fetch_array($result)){    
  array_push($res2, array(
  "name"=>$row['name'],
  "publisher"=>$row['username'],
  "image"=>$row['photo'],
 )
);}

If you have any tips, any comment or even a question (if I wasn't clear enough for you), just ask me ! Thanks !

Edit : What I want to make is an array of this type :

[{"name":"usera","publisher":"Jeana","image":"urla",""photouser","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","photouser","url2b"}]

  • 写回答

2条回答 默认 最新

  • dongtan9253 2018-05-07 10:34
    关注

    I finally achieve what I wanted to do, by using a replacement technic : With the foreach loop, I've created an array with the parameter profilepic, on the other array, I've created another parameter with a default value, then I replaced it. My code : First my foreach loop :

    foreach ( $restest as $user ) {
      if ( isset($photos[$user])) {
         array_push($res1, array(
         "profilepic"=>$photos[$user]));
     }
     else    {
       array_push($res1, array(
       "profilepic"=>'defaultvalue'));;
     };
    }
    

    and then I changed :

    while($row = mysqli_fetch_array($result)){    
      array_push($res2, array(
      "name"=>$row['name'],
      "publisher"=>$row['username'],
      "image"=>$row['photo'],
      "profilepic"=>'defaultvalue'
     )
    );}
    

    And finally I replaced it by :

    $res = array_replace_recursive($res2,$res1);
    

    So my final array with echo json_encode($res) is:

    [{"name":"usera","publisher":"Jeana","image":"urla",""profilepic","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","profilepic","defaultvalue"}]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题