简体   繁体   English

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

[英]Having trouble adding values to associative array php

I have an issue with adding value at the first position in an associative array, i've tried googling on the internet, used several methods to add a value but still it's not adding the value at the first position. 我在关联数组的第一个位置添加值时遇到问题,我尝试了在互联网上进行谷歌搜索,使用了几种方法添加值,但是仍然没有在第一个位置添加值。

what i tried is 我试过的是

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

but it doesn't work 但这不起作用

my PHP code: 我的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
      );


}

any suggestions? 有什么建议么? thanks! 谢谢!

Here is how you can prepend a value to an existing array. 这是您可以在现有数组之前添加值的方法。 You're correct to use unshift, but you probably want your static value to look like your DB records, and the first parameter for unshift should just be the target array. 您正确使用了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);

Please use this technique: 请使用此技术:

    $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