douzhan1031 2015-02-18 16:50
浏览 30
已采纳

无法将两个数组合并为一个来获取sql查询

Its might sounding like a noob question but I can't find an answer. Currently I have this.

$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $gridData[] = array(
                'CompanyName' => $row['CompanyName'],
                'ContactName' => $row['ContactName'],
                'ContactTitle' => $row['ContactTitle'],
            'Address' => $row['Address'],
            'Country' => $row['Country'],
            'Parent' => $row['Parent'],
            'City' => $row['City'],
            'id' => $row['id']
      );
}

but assuming I don't want to hardcode this fields there I have another array which is stored in $fields and has the structure of an array inside so field [0] is the fieldname.

so I do

 foreach ($fields as $field)
     {
       $gridData[$field[0]] => $row[$field[0]];
     }

by some reason it does not work like this. what is the way to do this properly? How can I bring this together?

  • 写回答

3条回答 默认 最新

  • duanchi6377 2015-02-18 17:07
    关注
    $gridData[] = array() 
    

    will add a numerical index to the $gridData array with value of what is in the array. You are trying to do

    $gridData[$field[0]] => $row[$field[0]];
    

    which is trying to reference a string index. Try:

    foreach ($gridData as $rowIndex => $gridRow){
      foreach ($fields as $field)
      {
        $gridData[$rowIndex][$field[0]] => $row[$field[0]];
      }
    }
    

    Alternatively, if you would be ok modifying your field data structure, you could use http://php.net/manual/en/function.array-merge.php

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

报告相同问题?

悬赏问题

  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考