我正在尝试从URL解析字符串并将其转换为PHP数组,但是到目前为止,我还无法使其正常工作。 该字符串包含逗号分隔的值,然后将这些值按句点分组,例如:
course.id,course.title,course.author,course.duration,course.trailer.video_key,course.trailer.duration,course.lessons.id,course.lessons.title,track.id,track.title,track.caption.srt,track.caption.vtt,track.caption.text
等效于此字符串的数组为:
PHP:
$array = [
'course' => [
'id',
'title',
'author',
'duration',
'trailer' => [
'video_key',
'duration'
],
'lessons' => [
'id',
'title'
]
],
'track' => [
'id',
'title',
'caption' => [
'srt',
'vtt',
'text'
]
]
];
我当前的解决方案是:
PHP:
$string = 'course.id,course.title,course.author,course.duration,course.trailer.video_key,course.trailer.duration,course.lessons.id,course.lessons.title,track.id,track.title,track.caption.srt,track.caption.vtt,track.caption.text';
$parameters = explode( ',', $string );
$array = array();
$inset = array();
foreach ( $parameters as $parameter ) {
$segments = explode( '.', $parameter );
if ( ! array_key_exists( $segments[0], $inset ) ) {
$array[ $segments[0] ] = array();
$inset[ $segments[0] ] = true;
}
$array[ $segments[0] ] = array_merge( $array[ $segments[0] ], addSegment( $segments, 1 ) );
}
function addSegment( $segments, $counter ) {
$results = array();
if ( end( $segments ) == $segments[ $counter ] ) {
return array( $segments[ $counter ] => null );
}
$results[ $segments[ $counter ] ] = addSegment( $segments, $counter + 1 );
return $results;
}
但是,这有点奏效;它失败,出现像这样的简单字符串
course,track,lessons
我认为这需要递归,但是我不太擅长写这篇文章,所以我希望有人已经这样做并且可以为我提供帮助。
谢谢。
答案 0 :(得分:1)
您无需递归即可实现此目的-只需执行两次循环并使用&
:
$arr = explode(",", "course.id,course.title,course.author,course.duration,course.trailer.video_key,course.trailer.duration,course.lessons.id,course.lessons.title,track.id,track.title,track.caption.srt,track.caption.vtt,track.caption.text");
foreach($arr as $e) {
$e = explode(".", $e);
$obj = &$res; //set the current place root
while(count($e) > 1) { // last element will be add as value
$key = array_shift($e);
if (!isset($obj[$key]))
$obj[$key] = [];
$obj = &$obj[$key]; //reset the current place
}
$obj[] = array_shift($e); // add the last as value to current place
}
$res
将包含您的愿望输出