我正在尝试重新排列数组中给出的数据,以便更易于管理
这是给定的数组
$config = array(
"themes" => array(
"0" => array(
"Name" => 'connect',
"Description" => 'Connect your song to the previous song by reusing a word in the artist or title.'
),
"1" => array(
"Name" => 'color',
"Description" => 'Play songs with a color in the artist name or song title, the song could also have something to do with color.'
)
)
);
这是所需的输出
$desired_config = array(
"themes" => array(
"connect" => array(
"0" => 'Connect your song to the previous song by reusing a word in the artist or title.'
),
"color" => array(
"0" => 'Play songs with a color in the artist name or song title, the song could also have something to do with color.'
)
)
);
这就是我试过的东西
foreach($config as $key=>$value){
if(is_array($value)){
foreach($value as $index=>$object){
if(is_array($object)){
foreach($object as $command){
$config[$key][$command['Name']][] = $command['Description'];
}
}else{
$config[$key] = $value;
}
}
}
}
print_r($config);
我的成绩非常糟糕
Array
(
[themes] => Array
(
[0] => Array
(
[Name] => connect
[Description] => Connect your song to the previous song by reusing a word in the artist or title.
)
[1] => Array
(
[Name] => color
[Description] => Play songs with a color in the artist name or song title, the song could also have something to do with color.
)
[c] => Array
(
[0] => c
[1] => c
)
[C] => Array
(
[0] => C
)
[P] => Array
(
[0] => P
)
)
答案 0 :(得分:2)
$desired_config = array();
foreach($config["themes"] as $index => $item) {
$desired_config["themes"][$item["Name"]] = array($item["Description"]);
}
print_r($desired_config);
答案 1 :(得分:1)
我认为这个功能可以满足您的需求:
function shiftMyArray($myArray) {
$ret = array();
foreach ($myArray as $key => $value){
if (is_array($value)){
$newArray = array();
foreach ($value as $index => $object){
if (is_array($object)){
$newArray[$object['Name']] = $object;
unset($newArray[$object['Name']]['Name']);
} else {
$newArray[$index] = $object;
}
}
$ret[$key] = $newArray;
} else {
$ret[$key] = $value;
}
}
return $ret;
}
var_dump($config, shiftMyArray($config));
答案 2 :(得分:1)
$new_config = array();
foreach ($config as $key=>$item) {
if (is_array($item)) {
$new_config[$key] = array();
foreach($item as $value) {
if (is_array($value) && array_key_exists('Name', $value) && array_key_exists('Description', $value)) {
$new_config[$key][$value['Name']] = array($value['Description']);
} else {
$new_config[$key][] = $value;
}
}
} else {
$new_config[$key] = $item;
}
}