繁体   English   中英

无法将值添加到关联数组php

[英]Having trouble adding values to associative array php

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

我试过的是

array_unshift($output_countries['CountryName'], "India");

但这不起作用

我的PHP代码:

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


}

有什么建议么? 谢谢!

这是您可以在现有数组之前添加值的方法。 您正确使用了unshift,但是您可能希望您的静态值看起来像您的数据库记录,并且unshift的第一个参数应该只是目标数组。

<?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);

请使用此技术:

    $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);

暂无
暂无

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

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