我在关联数组的第一个位置添加值时遇到了问题,我尝试在互联网上搜索,使用了几种方法来添加值,但仍然没有在第一个位置添加值。
我尝试的是
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
);
}有什么建议吗?谢谢!
发布于 2019-05-14 11:12:38
下面是如何将值添加到现有数组的方法。您使用unshift是正确的,但是您可能希望您的静态值看起来像您的DB记录,并且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);发布于 2019-05-14 12:18:46
请使用以下技巧:
$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);https://stackoverflow.com/questions/56122255
复制相似问题