PHP 2d数组推送问题
我左右为难 这是我想要的输出PHP 2d数组推送问题,php,arrays,laravel-5,array-push,Php,Arrays,Laravel 5,Array Push,我左右为难 这是我想要的输出 Array ( [country] => Array( [0] => England [1] => Channel Islands ) [gor] => Array( [0] => North East [1] => North West
Array
(
[country] => Array(
[0] => England
[1] => Channel Islands
)
[gor] => Array(
[0] => North East
[1] => North West
)
[parliamentaryconstituency] => Array(
[0] => Aldershot
[1] => Aldridge-Brownhills
)
)
这就是我现在拥有的
Array
(
[0] => Array
(
[country] => England
)
[1] => Array
(
[country] => Channel Islands
)
[2] => Array
(
[gor] => North East
)
[3] => Array
(
[gor] => North West
)
[4] => Array
(
[parliamentaryconstituency] => Aldershot
)
[5] => Array
(
[parliamentaryconstituency] => Aldridge-Brownhills
)
)
我的代码是
foreach ($input as $key => $value) {
foreach ($value as $subkey => $subvalue) {
switch ($key)
{
case 'country':
$country = Country::description($subvalue)->get()->first();
array_push($new_input, array('country' => $country->description));
break;
case 'gor':
$gor = Gor::description($subvalue)->get()->first();
array_push($new_input, array('gor' => $gor->description));
break;
case 'parlc':
$parliamentaryconstituency = ParliamentaryConstituency::description($subvalue)->get()->first();
array_push($new_input, array('parliamentaryconstituency' => $parliamentaryconstituency->description));
break;
}
}
}
我考虑了
array\u push($new\u input['country',$country->description)
并在foreach
上方具有$new\u input['country']
,但如果未选择任何国家,则将输出一个空的国家/地区数组,如果是这种情况,我希望它根本不出现。您可以尝试以下方法:
$result = array();
foreach ($input as $key => $value) {
foreach ($value as $subkey => $subvalue) {
switch ($key)
{
case 'country':
$country = Country::description($subvalue)->get()->first();
if ($country) {
$result['country'][] = $country;
}
break;
case 'gor':
$gor = Gor::description($subvalue)->get()->first();
if ($gor) {
$result['gor'][] = $gor;
}
break;
case 'parlc':
$parliamentaryconstituency = ParliamentaryConstituency::description($subvalue)->get()->first();
if ($parliamentaryconstituency) {
$result['parliamentaryconstituency'][] = $parliamentaryconstituency;
}
break;
}
}
}
print_r($result);
数组\始终在数组末尾添加新元素。相反,使用如下所示的所有键初始化数组
$result = array("country" => array(), "gor" => array(), etc);
在循环中,假设要插入的值是$value do
$result[$key][] = $value
或者,如果您更喜欢使用array\u push
array_push($result[$key], $value);
'$list=array();'
/add array value
'array_push($list,array("name"=>"jone","surname"=>"doe"));'
//get array value
'$list[index][columnname]'