Php 在现有阵列中添加新阵列时阵列形成不正确
我正在尝试将数组添加到现有数组中。它被添加了,但是数组中的数组就是它的输出 当前情景Php 在现有阵列中添加新阵列时阵列形成不正确,php,foreach,Php,Foreach,我正在尝试将数组添加到现有数组中。它被添加了,但是数组中的数组就是它的输出 当前情景 Array ( [t373980] => stdClass Object ( [tid] => 373980 [name] => Ability [depth] => 0 [startMo
Array
(
[t373980] => stdClass Object
(
[tid] => 373980
[name] => Ability
[depth] => 0
[startMonday] => 0
[hidden_name] => selected_agency[373980]
[parent_tid] => 0
[full_label] => Ability
[full_tid] => 373980
[expanded] => 0
)
[t414605] => stdClass Object
(
[tid] => 414605
[name] => Ad Council
[depth] => 0
[startMonday] => 0
[hidden_name] => selected_agency[414605]
[parent_tid] => 0
[full_label] => Ad Council
[full_tid] => 414605
[expanded] => 0
)
[t0] => stdClass Object
(
[t] => Array
(
[tid] => 0
[name] => (Blank)
[depth] => 0
[startMonday] => 0
[hidden_name] => selected_agency[0]
[parent_tid] => 0
[full_label] => (Blank)
[full_tid] => 0
[expanded] => 0
)
)
)
**我想要的是**
Array
(
[t373980] => stdClass Object
(
[tid] => 373980
[name] => Ability
[depth] => 0
[startMonday] => 0
[hidden_name] => selected_agency[373980]
[parent_tid] => 0
[full_label] => Ability
[full_tid] => 373980
[expanded] => 0
)
[t414605] => stdClass Object
(
[tid] => 414605
[name] => Ad Council
[depth] => 0
[startMonday] => 0
[hidden_name] => selected_agency[414605]
[parent_tid] => 0
[full_label] => Ad Council
[full_tid] => 414605
[expanded] => 0
)
[t] => stdClass Object
(
[tid] => 0
[name] => (Blank)
[depth] => 0
[startMonday] => 0
[hidden_name] => selected_agency[0]
[parent_tid] => 0
[full_label] => (Blank)
[full_tid] => 0
[expanded] => 0
)
)
$no_agency_arr =array("tid"=>"0", "name"=>"(Blank)", "depth"=>0, "startMonday"=>0, "hidden_name"=>"selected_agency[0]",
"parent_tid"=>"0", "full_label"=>"(Blank)", "full_tid"=>"0", "expanded"=>0);
$no_agency_obj = (object)$no_agency_arr;
$final_no_agency_arr["t"] = $no_agency_obj;
array_push($out,$final_no_agency_arr);
在你的代码中替换这个
$no_agency_obj = (object)$no_agency_arr;
$final_no_agency_arr["t"] = $no_agency_obj;
用这个
$final_no_agency_arr["t"] = $no_agency_arr;
如果您只需要一个数组,则无需创建对象
$no_agency_arr =array("tid"=>"0", "name"=>"(Blank)", "depth"=>0, "startMonday"=>0, "hidden_name"=>"selected_agency[0]",
"parent_tid"=>"0", "full_label"=>"(Blank)", "full_tid"=>"0", "expanded"=>0);
//you need array so no need to convert it to object. so comment/remove it out.
//$no_agency_obj = (object)$no_agency_arr;
$final_no_agency_arr["t"] = $no_agency_arr;
//why are you using it when you already assigned value in that array. so comment it,
//if `$out` if the final array which you are printing, so you need to assign value in it instead of `$final_no_agency_arr` like:
$out["t"] = $no_agency_arr; //don't forget to comment out the above line
//array_push($out,$final_no_agency_arr);
我需要将其转换为object,其背后的目的是什么?你能解释一下吗?它被添加到了数组的底部。我需要在第一个位置。您可以使用
array\u unshift()-将一个或多个元素前置到数组的开头
,但键会有所不同-或者您可以在$final\u no\u agency\u arr[“t”=$no\u agency\u arr]之后使用ksort($final\u no\u agency\u arr)
代码>