Advertisement
Guest User

Untitled

a guest
Dec 4th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: npisarev
  5. * Date: 03/12/2016
  6. * Time: 11:46
  7. */
  8.  
  9. $data1 = [
  10. 'parent.child.field' => 1,
  11. 'parent.child.field2' => 2,
  12. 'parent2.child.name' => 'test',
  13. 'parent2.child2.name' => 'test',
  14. 'parent2.child2.position' => 10,
  15. 'parent3.child3.position' => 10,
  16. ];
  17.  
  18. $data = [
  19. 'parent' => [
  20. 'child' => [
  21. 'field' => 1,
  22. 'field2' => 2,
  23. ],
  24. ],
  25. 'parent2' => [
  26. 'child' => [
  27. 'name' => 'test',
  28. ],
  29. 'child2' => [
  30. 'name' => 'test',
  31. 'position' => 10,
  32. ],
  33. ],
  34. 'parent3' => [
  35. 'child3' => [
  36. 'position' => 10,
  37. ],
  38. ],
  39. ];
  40.  
  41. function constructive(array $data)
  42. {
  43. $result = [];
  44. foreach ($data as $key => $value) {
  45. list($parent, $child, $arg) = explode('.', $key);
  46. $result[$parent][$child][$arg] = $value;
  47. }
  48.  
  49. return $result;
  50. }
  51.  
  52.  
  53. function recursive(array $data, $keys = [])
  54. {
  55. $result = [];
  56. foreach ($data as $key => $value) {
  57. if (is_array($value)) {
  58. $keys[] = $key;
  59. $result = array_merge($result, recursive($value, $keys));
  60. array_pop($keys);
  61. continue;
  62. }
  63. $resKey = implode('.', $keys);
  64. $result[$resKey . '.' .$key] = $value;
  65. }
  66. return $result;
  67. }
  68.  
  69. print_r(constructive($data1));
  70.  
  71. print_r(recursive($data));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement