XML parsing conundrum

后端 未结 7 1558
甜味超标
甜味超标 2021-01-15 22:25

UPDATE: I\'ve reworked the question, to show progress I\'ve made, and maybe make it easier to answer.

UPDATE 2: I\'ve added another value to the XML. Extension avail

7条回答
  •  梦谈多话
    2021-01-15 22:59

    You are merely mapping the input values into the output array by arranging them differently, this is your structure:

    Array(
      [... Item/Platform] => Array (
        [... Item/Title as 0-n] => array(
            "Name" => Item/Name,
            "Title" => Item/Title,
            "Files" => array(
                [...] => array(
                    "DownloadPath" => Item/DownloadPath
                ),
            )
        ),
    

    The mapping can be done by iterating over the items within the XML and storing the values into the appropriate place in the new array (I named it $build):

    $build = array();
    foreach($items as $item)
    {
        $platform = (string) $item->Platform;
        $title = (string) $item->Title;
        isset($build[$platform][$title]) ?: $build[$platform][$title] = array(
            'Name' => (string) $item->Name,
            'Title' => $title
        );
        $build[$platform][$title]['Files'][] = array('DownloadPath' => (string) $item->DownloadPath);
    }
    $build = array_map('array_values', $build);
    

    The array_map call is done at the end to convert the Item/Title keys into numerical ones.

    And that's it, here the Demo.

    Let me know if that's helpful.

    Edit: For your updated data, it's a slight modification of the above, the key principles of the previous example still exist, it's additionally taken care of the extra duplication per each additional extension per item, by adding another iteration inside:

    $build = array();
    foreach($items as $item)
    {
        $platform = (string) $item->Platform;
        $title = (string) $item->Title;
        foreach(preg_split("~\s+~", $item->Ext) as $ext)
        {
            isset($build[$platform][$ext][$title])
                ?:$build[$platform][$ext][$title] = array(
                    'Name' => (string) $item->Name,
                    'Title' => $title
                );
            $build[$platform][$ext][$title]['Files'][]
                = array('DownloadPath' => (string) $item->DownloadPath);
        }
    }
    $build = array_map(function($v) {return array_map('array_values', $v);}, $build);
    

提交回复
热议问题