首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >向关联数组php添加值时遇到问题

问向关联数组php添加值时遇到问题
EN

Stack Overflow用户
提问于 2019-05-14 10:36:00
回答 2查看 20关注 0票数 0

我在关联数组的第一个位置添加值时遇到了问题,我尝试在互联网上搜索,使用了几种方法来添加值,但仍然没有在第一个位置添加值。

我尝试的是

代码语言:javascript
复制
array_unshift($output_countries['CountryName'], "India");

但它不起作用

我的PHP代码:

代码语言:javascript
复制
while($rows_fetch_country_list = mysql_fetch_array($query_country_list)) {
    extract($rows_fetch_country_list);


      $output_countries[] = array(
           "CountryName" => $country_name,
           "CountryCode" => $country_code,
           "Id" => $pk_country_id
      );


}

有什么建议吗?谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-14 11:12:38

下面是如何将值添加到现有数组的方法。您使用unshift是正确的,但是您可能希望您的静态值看起来像您的DB记录,并且unshift的第一个参数应该只是目标数组。

代码语言:javascript
复制
<?php
//Your static record
$staticCountry = ['CountryName' => 'India',  'CountryCode' => 'IN', 'Id' => 0];

//Results from DB
$countries = [
    ['CountryName' => 'Canada',  'CountryCode' => 'CA', 'Id' => 1],
    ['CountryName' => 'France',  'CountryCode' => 'FR', 'Id' => 2],
    ['CountryName' => 'Germany',  'CountryCode' => 'DE', 'Id' => 3]
];    

array_unshift($countries, $staticCountry);
票数 1
EN

Stack Overflow用户

发布于 2019-05-14 12:18:46

请使用以下技巧:

代码语言:javascript
复制
    $country[0] = array("Nepal" => "Nepal", "CountryCode" => 'NP',"Id" => 01);
    $country[1] = array("India" => "India", "CountryCode" => 'IN',"Id" => 02);
    $firstItem[0] = array('Pakistan' => 'Pakistan',"CountryCode" => 'PK',"Id" => 03);

    $arr= array_merge($firstItem, $country);
    print_r($arr);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56122255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档