来自扁平JSON

时间:2017-05-16 22:06:08

标签: php arrays json

我有一个数据库查询,它为我提供了一些员工数据的输出。我想使用此数据传递给生成组织结构图的插件。我正在提取的JSON对象中有一些字段是:

FirstName
LastName
EmployeeID
ManagerEmployeeID
Manager Name

数据作为平面JSON对象返回,在层次结构中员工及其经理之间没有嵌套或关联。

由于我无法更改源数据(数据库查询)的输出,因此我试图找到一种嵌套数据的方法,以便JSON输出成为嵌套输出。

我的目标是获取此数组并基于ManagerID和EmployeeID将其嵌套,以便我可以创建树层次结构。

示例数据:

•   Tom Jones
   o    Alice Wong
   o    Tommy J.
•   Billy Bob
   o    Rik A.
     ♣  Bob Small
     ♣  Small Jones
   o    Eric C.

我的平面数据示例:

    {
        "FirstName": "Tom"
        "LastName": "Jones"
        "EmployeeID": "123"
        "ManagerEmployeeID": ""
        "Manager Name": ""
    },
    {
        "FirstName": "Alice"
        "LastName": "Wong"
        "EmployeeID": "456"
        "ManagerEmployeeID": "123"
        "Manager Name": "Tom Jones"
    },
    {
        "FirstName": "Tommy"
        "LastName": "J."
        "EmployeeID": "654"
        "ManagerEmployeeID": "123"
        "Manager Name": "Tom Jones"
    },
    {
        "FirstName": "Billy"
        "LastName": "Bob"
        "EmployeeID": "777"
        "ManagerEmployeeID": ""
        "Manager Name": ""
    },
    {
        "FirstName": "Rik"
        "LastName": "A."
        "EmployeeID": "622"
        "ManagerEmployeeID": "777"
        "Manager Name": "Billy Bob"
    },
    {
        "FirstName": "Bob"
        "LastName": "Small"
        "EmployeeID": "111"
        "ManagerEmployeeID": "622"
        "Manager Name": "Rik A."
    },
    {
        "FirstName": "Small"
        "LastName": "Jones"
        "EmployeeID": "098"
        "ManagerEmployeeID": "622"
        "Manager Name": "Rik A"
    },
    {
        "FirstName": "Eric"
        "LastName": "C."
        "EmployeeID": "222"
        "ManagerEmployeeID": "777"
        "Manager Name": "Billy Bob"
    }

示例所需输出:

[
  {
    "FirstName": "Tom",
    "LastName": "Jones",
    "EmployeeID": "123",
    "ManagerEmployeeID": "",
    "Manager Name": "",
    "employees": [
      {
        "FirstName": "Alice",
        "LastName": "Wong",
        "EmployeeID": "456",
        "ManagerEmployeeID": "123",
        "Manager Name": "Tom Jones"
      },
      {
        "FirstName": "Tommy",
        "LastName": "J.",
        "EmployeeID": "654",
        "ManagerEmployeeID": "123",
        "Manager Name": "Tom Jones"
      }
    ]
  },
  {
    "FirstName": "Billy",
    "LastName": "Bob",
    "EmployeeID": "777",
    "ManagerEmployeeID": "",
    "Manager Name": "",
    "employees": [
      {
        "FirstName": "Rik",
        "LastName": "A.",
        "EmployeeID": "622",
        "ManagerEmployeeID": "777",
        "Manager Name": "Billy Bob",
        "employees": [
          {
            "FirstName": "Bob",
            "LastName": "Small",
            "EmployeeID": "111",
            "ManagerEmployeeID": "622",
            "Manager Name": "Rik A."
          },
          {
            "FirstName": "Small",
            "LastName": "Jones",
            "EmployeeID": "098",
            "ManagerEmployeeID": "622",
            "Manager Name": "Rik A"
          }
        ]
      },
      {
        "FirstName": "Eric",
        "LastName": "C.",
        "EmployeeID": "222",
        "ManagerEmployeeID": "777",
        "Manager Name": "Billy Bob"
      }
    ]
  }
]

实际上,我试图使用EmployeeIDManagerEmployeeID作为两者之间的链接,从平面对象创建嵌套的JSON输出。

用PHP解决这类问题的最佳方法是什么?

赏金更新:

以下是该问题的测试用例:https://eval.in/private/4b0635c6e7b059

您将看到名称为Issue Here的最后一条记录未显示在结果集中。这个managerID与根节点匹配,应该在" Tom Jones" employees数组。

4 个答案:

答案 0 :(得分:6)

我有以下实用程序类可以完全满足您的需要。

class NestingUtil
{
    /**
     * Nesting an array of records using a parent and id property to match and create a valid Tree
     *
     * Convert this:
     * [
     *   'id' => 1,
     *   'parent'=> null
     * ],
     * [
     *   'id' => 2,
     *   'parent'=> 1
     * ]
     *
     * Into this:
     * [
     *   'id' => 1,
     *   'parent'=> null
     *   'children' => [
     *     'id' => 2
     *     'parent' => 1,
     *     'children' => []
     *    ]
     * ]
     *
     * @param array  $records      array of records to apply the nesting
     * @param string $recordPropId property to read the current record_id, e.g. 'id'
     * @param string $parentPropId property to read the related parent_id, e.g. 'parent_id'
     * @param string $childWrapper name of the property to place children, e.g. 'children'
     * @param string $parentId     optional filter to filter by parent
     *
     * @return array
     */
    public static function nest(&$records, $recordPropId = 'id', $parentPropId = 'parent_id', $childWrapper = 'children', $parentId = null)
    {
        $nestedRecords = [];
        foreach ($records as $index => $children) {
            if (isset($children[$parentPropId]) && $children[$parentPropId] == $parentId) {
                unset($records[$index]);
                $children[$childWrapper] = self::nest($records, $recordPropId, $parentPropId, $childWrapper, $children[$recordPropId]);
                $nestedRecords[] = $children;
            }
        }

        return $nestedRecords;
    }
}

使用您的代码:

$employees = json_decode($flat_employees_json, true);
$managers = NestingUtil::nest($employees, 'EmployeeID', 'ManagerEmployeeID', 'employees');
print_r(json_encode($managers));

输出:

[
  {
    "FirstName": "Tom",
    "LastName": "Jones",
    "EmployeeID": "123",
    "ManagerEmployeeID": "",
    "Manager Name": "",
    "employees": [
      {
        "FirstName": "Alice",
        "LastName": "Wong",
        "EmployeeID": "456",
        "ManagerEmployeeID": "123",
        "Manager Name": "Tom Jones",
        "employees": []
      },
      {
        "FirstName": "Tommy",
        "LastName": "J.",
        "EmployeeID": "654",
        "ManagerEmployeeID": "123",
        "Manager Name": "Tom Jones",
        "employees": []
      }
    ]
  },
  {
    "FirstName": "Billy",
    "LastName": "Bob",
    "EmployeeID": "777",
    "ManagerEmployeeID": "",
    "Manager Name": "",
    "employees": [
      {
        "FirstName": "Rik",
        "LastName": "A.",
        "EmployeeID": "622",
        "ManagerEmployeeID": "777",
        "Manager Name": "Billy Bob",
        "employees": [
          {
            "FirstName": "Bob",
            "LastName": "Small",
            "EmployeeID": "111",
            "ManagerEmployeeID": "622",
            "Manager Name": "Rik A.",
            "employees": []
          },
          {
            "FirstName": "Small",
            "LastName": "Jones",
            "EmployeeID": "098",
            "ManagerEmployeeID": "622",
            "Manager Name": "Rik A",
            "employees": []
          }
        ]
      },
      {
        "FirstName": "Eric",
        "LastName": "C.",
        "EmployeeID": "222",
        "ManagerEmployeeID": "777",
        "Manager Name": "Billy Bob",
        "employees": []
      }
    ]
  }
]
  

Edit1:修复以避免忽略某些员工

     

如果最后一项是具有有效经理的员工,但经理不在列表中,则会被忽略,因为应该位于哪里?,它不是根,但没有有效的经理。

为避免这种情况,请在实用程序中的return语句之前添加以下行。

if (!$parentId) {
    //merge residual records with the nested array
    $nestedRecords = array_merge($nestedRecords, $records);
}

return $nestedRecords;
  

Edit2:将实用程序更新为PHP5.6

在PHP7中进行一些测试后,该实用程序在php7.0中工作正常但在php5.6中没有,我不知道为什么,但是在数组引用和未设置中。我更新实用程序代码以使用php5.6和您的用例。

 public static function nest($records, $recordPropId = 'id', $parentPropId = 'parent_id', $childWrapper = 'children', $parentId = null)
    {
        $nestedRecords = [];
        foreach ($records as $index => $children) {
            if (isset($children[$parentPropId]) && $children[$parentPropId] == $parentId) {
                $children[$childWrapper] = self::nest($records, $recordPropId, $parentPropId, $childWrapper, $children[$recordPropId]);
                $nestedRecords[] = $children;
            }
        }

        if (!$parentId) {
            $employeesIds = array_column($records, $recordPropId);
            $managers = array_column($records, $parentPropId);
            $missingManagerIds = array_filter(array_diff($managers, $employeesIds));
            foreach ($records as $record) {
                if (in_array($record[$parentPropId], $missingManagerIds)) {
                    $nestedRecords[] = $record;
                }
            }
        }

        return $nestedRecords;
    }

答案 1 :(得分:1)

这是从你的小提琴直接翻译到PHP:

function makeTree($data, $parentId){
    return array_reduce($data,function($r,$e)use($data,$parentId){
        if(((empty($e->ManagerEmployeeID)||($e->ManagerEmployeeID==(object)[])) && empty($parentId)) or ($e->ManagerEmployeeID == $parentId)){
            $employees = makeTree($data, $e->EmployeeID);
            if($employees) $e->employees = $employees;
            $r[] = $e;
        }
        return $r;
    },[]);
}

它可以正确处理您的测试输入。 请参阅https://eval.in/private/ee9390e5e8ca95

使用示例:

$nested = makeTree(json_decode($json), '');
echo json_encode($nested, JSON_PRETTY_PRINT);

@rafrsr解决方案非常灵活,但问题是unset()内的foreach。 它在迭代时修改数组,这是一个坏主意。 如果您删除了unset(),它就能正常运行。

答案 2 :(得分:1)

你可以在这里使用递归的神奇力量。请参考以下示例。 正如您在此处所见,正在调用 getTreeData

function getTreeData($data=[], $parent_key='', $self_key='', $key='')
{
    if(!empty($data))
    {

        $new_array = array_filter($data, function($item) use($parent_key, $key) {

            return $item[$parent_key] == $key;
        });

        foreach($new_array as &$array)
        {
            $array["employees"] = getTreeData($data, $parent_key, $self_key, $array[$self_key]);

            if(empty($array["employees"]))
            {
                unset($array["employees"]);
            }
        }

        return $new_array;
    }
    else
    {
        return $data;
    }
}

$employees = json_decode($employees_json_string, true);

$employees_tree = getTreeData($employees, "ManagerEmployeeID", "EmployeeID");

答案 3 :(得分:0)

这是一个巧妙的技巧,利用对象通过引用传递的事实。

array_column首先用于通过EmployeeID重新输入输入数组。 然后使用array_map迭代条目并将每个项目重新分配给相应管理器的employees数组。由于条目是对象(stdClass),因此正在修改相同的输入项。

通过引用添加到employees数组的项目在根级别为空。然后使用array_filter删除这些空条目。最后,array_values删除了临时EmployeeID键控。

$input = json_decode($flat_employees_json, true);
$input = array_column($input, null, "EmployeeID");
$input = array_map(function ($entry) {
    return (object) $entry;
}, $input);
$output = array_values(array_filter(array_map(function ($entry) use ($input) {
    if (!empty($entry->ManagerEmployeeID)) {
        $input[$entry->ManagerEmployeeID]->employees[] = $entry;
        return null;
    }
    return $entry;
}, $input)));
echo json_encode($output, JSON_PRETTY_PRINT);

试试online

PHP 7支持array_column的对象数组,因此输入初始化可以简化为:

$input = array_column(json_decode($flat_employees_json), null, "EmployeeID");