如何将键设置为数组的值 - php

时间:2015-05-22 14:30:51

标签: php arrays

我想设置一个键到我的数组的父值。

我的输出是父值和数组;

"parent":{

'A'=>value,

'B'=>value

}

输出(读取输出复制/粘贴到http://json.parser.online.fr/):

{"7916":{"id":"1168","GoodMainCode":"7916","title":"\u0632\u064a\u0631\u062f\u0633\u062a\u064a \u0637\u0644\u0642\u064a CLIP BOARD","author":" ","publisher":"\u0641\u0642\u064a\u0647\u064a \u0645\u0647\u0631","translator":" ","price":"20625","isbn":" ","amount":"0","year_of_publish":"0","period_print":"0"},"7989":{"id":"16827","GoodMainCode":"7989","title":"\u064a\u062f\u0643 \u0627\u062a\u0648\u062f5\u0645\u064a\u0644 \u0643\u0648\u0647 \u0646\u0648\u0631B6","author":" ","publisher":"","translator":" ","price":"108025","isbn":" ","amount":61,"year_of_publish":"0","period_print":"0"},"8350":{"id":"1225","GoodMainCode":"8350","title":"\u064a\u062f\u0643 \u0627\u062a\u0648\u062f\u0637\u0631\u0627\u062d\u064a2\u0645\u064a\u0644JBN","author":" ","publisher":"","translator":" ","price":"3375","isbn":" ","amount":"0","year_of_publish":"0","period_print":"0"}}

现在,我想将密钥设置为7916,7989,8350。喜欢:

"mykey"=>"parent":{

'A'=>value,
'B'=>value

}

我该怎么做?

我的职能:

    while($row = $stmt->fetch()){

        $arr = array(
            'id'=>persian_sql_to_php($row['row1']),
            'GoodMainCode'=>persian_sql_to_php($row['GoodMainCode']),
            'title'=> persian_sql_to_php($row['GoodName']),
            'author'=>persian_sql_to_php($row['moalef']),
            'publisher'=>persian_sql_to_php($row['Nasher']),
            'translator'=>persian_sql_to_php($row['Motarjem']),
            'price'=>persian_sql_to_php($row['SellPrice1']),
            'isbn'=>persian_sql_to_php($row['ISBN']),
            'amount'=>persian_sql_to_php($row['Amount']),
            'year_of_publish'=>persian_sql_to_php($row['SaleChap']),
            'period_print'=>persian_sql_to_php($row['NobateChap'])
        );


        array_push($mjson,$arr);

    }



  foreach($mjson as $v){

      if(!isset($result[$v['GoodMainCode']])){
          $result[$v['GoodMainCode']] = $v;
      }
      else
          $result[$v['GoodMainCode']]['amount'] += $v['amount'];
  }

1 个答案:

答案 0 :(得分:0)

您正在进行通用推送操作,这可让php找出密钥应该是什么。您需要明确设置密钥:

while($row = ...) {
   $arr[$row['row1']] = $row;
        ^^^^^^^^^^^^---id value from database
}

只要row1值是您正在获取的记录的主键,您就会以每行的数组条目结束。如果row ISN&T; T唯一,则会使用新行覆盖以前的值。