Search code examples
phparrays

Create array from string containing parent and child separators


I am trying to figure out how to convert this string to an array, while also not repeating "parent" keys. The parent seperater is | while child seperator is >.

Example string: Progressivism and World War 1>Gender and Equality|Progressivism and World War 1>Social Change and Reform|The Great Depression and the New Deal

In the above example "Progressivism and World War 1" has two children, namely: "Gender and Equality" and "Social Change and Reform".

End result should be:

[0] => [
  'name'   => 'Progressivism and World War 1'
  'parent' => false
],
[1] => [
  'name' => 'Gender and Equality'
  'parent' => 'Progressivism and World War 1'
],
[2] => [
  'name' => 'Social Change and Reform'
  'parent' => 'Progressivism and World War 1'
],
[3] => [
  'name' => 'The Great Depression and the New Deal'
  'parent' => false
],

Solution

  • First, you have to split your string into multiple parts to get the different parts you need to build the array. You can do this in PHP with explode(string delimiter, string input).

    Then, loop through them and do the same again. Before adding to the array, check if there is a parent, if not set parent to false.

    That's the solution I came up with:

    <?php
    
    $input = "Progressivism and World War 1>Gender and Equality|Progressivism and World War 1>Social Change and Reform|The Great Depression and the New Deal";
    $result = [];
    
    $parents = explode('|', $input);
    
    foreach($parents as $parent) {
        $childs = explode(">", $parent);
        if(count($childs) === 1) {
            $result [] = [
                'name' => $childs[0],
                'parent' => false
            ];
        } else {
            $result [] = [
                'name' => $childs[1],
                'parent' => $childs[0]
            ];
        }
    }