首页 > 解决方案 > 无法将值添加到关联数组 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
      );


}

有什么建议么?谢谢!

标签: phparrays

解决方案


以下是如何为现有数组添加值。使用 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);

推荐阅读