0

I am trying to fetch keys of array separately and values separately. actual output:

[  
   "IT" => [  
      "Programming" => [  
         0 => "Python" 1 => "Java"
      ],
      "Networking" =>  [  
         0 => "CCNA"
      ]
   ],
   "Business" => [  
      "Power BI" => [  
         0 => "Power BI foundation"
      ]
   ]
]

desired output:

[  
   "IT",
   "Business"
]
[  
   "Programming",
   "Networking"
]
9
  • 1
    What code did you use to fetch/generate those data? Also please explain the logic to group those keys together. Commented Apr 13, 2019 at 9:08
  • i am trying to fetch data from database using foreach loop to separate category, subcategory and product Commented Apr 13, 2019 at 9:14
  • Like catcon said, what is the logic to group those keys together? Commented Apr 13, 2019 at 9:20
  • i have an array which includes categories-sub categories and then items . Now i want to show this data on my blade in related manner . So what can be the code to do so? Commented Apr 13, 2019 at 9:28
  • basically to be more specific the array shows the relation between category, sub-category and product. To get keys my logic, to separate categories, subcategories and product. Commented Apr 13, 2019 at 9:39

1 Answer 1

1

Does this script what you need?

$arr = [  
   "IT" => [  
      "Programming" => [  
         0 => "Python",
         1 => "Java"
      ],
      "Networking" =>  [  
         0 => "CCNA"
      ]
   ],
   "Business" => [  
      "Power BI" => [  
         0 => "Power BI foundation"
      ]
   ]
];

$categories = [];
$subcategories = [];

foreach($arr as $key => $value) {
    array_push($categories, $key);
    array_push($subcategories, array_keys($value));
}

$categories equals:

["IT","Business"]

$subcategories equals :

[
  ["Programming","Networking"],
  ["Power BI"]
]

after execution.

Nevertheless, I would recommend to restructure your fetch script that has the array contained in $arr as output to avoid unnecessary loops.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.