我在json_decode(string,true)之后确实有以下关联多维数组。
Array
(
[statusCode] => 200
[data] => Array
(
[objects] => Array
(
[0] => deals
[1] => contacts
[2] => accounts
)
[deals] => Array
(
[0] => dealName
[1] => ApprovedBy
[2] => ApprovedDate
[3] => CloseDate
)
[contacts] => Array
(
[0] => contectName
[1] => email
[2] => firstName
[3] => lastName
)
[accounts] => Array
(
[0] => accountName
[1] => creationDate
[2] => ApprovedDate
[3] => accountNumber
)
)
)
它希望将数字键替换为数组中的相应值,如:
[deals] => deals
[contacts] => contacts
[accounts] => accounts
到目前为止我尝试了什么?
$finalIOArray = array();
$integrationObjectsArray = $response['data']['objects'];
foreach($integrationObjectsArray as $integrationObject){
$finalIOArray[$integrationObject] = $integrationObject;
}
这仅适用于主数据阵列中的对象数组。但我想用主数据数组中所有子数组中的值替换键。
答案 0 :(得分:2)
你可以这样做
foreach($arr["data"] as $key=>&$data){
$new = array();
foreach($data as $key2=>$value){
$new[$value] = $value;
}
$data = $new;
}
print_r($arr);
答案 1 :(得分:2)
这是问题的递归解决方案
file
答案 2 :(得分:1)
我修改我的代码以满足您的需求,请尝试一下。
$data = [];
foreach($arr["data"] as $key => $example) {
$new = [];
foreach($example as $value) {
$new[$value] = $value;
}
$data[$key] = $new;
}
$arr["data"] = $data;
print_r($arr);
答案 3 :(得分:0)
这是一种比其他提供的更清洁,更直接的方法。使用array_combine使用子数组中的值批量重新分配键。
在使用foreach的方法中,&
之前的$data
表示“通过引用传递”。 http://php.net/manual/en/language.references.pass.php这有效地允许修改原始数组数据,而无需编写通向特定深层元素的键。
代码:
$arr = Array
(
"statusCode" => 200,
"data" => Array
(
"objects" => Array
(
"0" => deals,
"1" => contacts,
"2" => accounts
),
"deals" => Array
(
"0" => dealName,
"1" => ApprovedBy,
"2" => ApprovedDate,
"3" => CloseDate
),
"contacts" => Array
(
"0" => contectName,
"1" => email,
"2" => firstName,
"3" => lastName
),
"accounts" => Array
(
"0" => accountName,
"1" => creationDate,
"2" => ApprovedDate,
"3" => accountNumber
)
)
);
foreach($arr["data"] as &$data){
$data=array_combine($data,$data);
}
var_export($arr);
输出:
array (
'statusCode' => 200,
'data' =>
array (
'objects' =>
array (
'deals' => 'deals',
'contacts' => 'contacts',
'accounts' => 'accounts',
),
'deals' =>
array (
'dealName' => 'dealName',
'ApprovedBy' => 'ApprovedBy',
'ApprovedDate' => 'ApprovedDate',
'CloseDate' => 'CloseDate',
),
'contacts' =>
array (
'contectName' => 'contectName',
'email' => 'email',
'firstName' => 'firstName',
'lastName' => 'lastName',
),
'accounts' =>
array (
'accountName' => 'accountName',
'creationDate' => 'creationDate',
'ApprovedDate' => 'ApprovedDate',
'accountNumber' => 'accountNumber',
),
),
)
或者如果您更喜欢功能迭代,则会提供相同的输出。
$arr["data"]=array_map(function ($a){return array_combine($a,$a);},$arr["data"]);
var_export($arr);