I'm sorry about the title, but I don't know how to explain it on Title. So, here's my case.
I Had a table
id | category | subcategory |
---|---|---|
1 | 1 | Apple |
2 | 1 | Orange |
3 | 2 | Car |
4 | 2 | Motorcycle |
What I want to do is, doing some loop and the output is like this in PHP
<script type="text/javascript">
const subkategoris = {
"1":[
{value:1,desc:"Apple"},
{value:2,desc:"Orange"},
],
"2":[
{value:3,desc:"Car"},
{value:4,desc:"Motorcycle"},
],
...etc
</script>
I already trying to loop it but, what I got is like this
<script type="text/javascript">
const subkategoris = {
"1":[
{value:1,desc:"Apple"},
],
"1":[
{value:2,desc:"Orange"},
],
"2":[
{value:3,desc:"Car"},
],
"2":[
{value:4,desc:"Motorcycle"},
...etc
</script>
Can somebody help me?
CodePudding user response:
It's not clear what you want to achieve and in what language. You're asking for PHP solution but all the code in JS.
Here it is a JS solution of what I understand you're trying to do
const initialData = [
{
id: 1,
category: 1,
subCategory: 'Apple'
},{
id: 2,
category: 1,
subCategory: 'Orange'
},{
id: 3,
category: 2,
subCategory: 'Car'
},{
id: 4,
category: 2,
subCategory: 'Motorcycle'
},
]
const groupedByCategory = initialData.reduce((res, {id, category, subCategory}) => {
const existing = res[category] || []
return {
...res,
[category] : [...existing, {value: id, desc: subCategory}]
}
}, {});
console.log(groupedByCategory)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
You can do the same in PHP using array_reduce
$data = [...]; // array with the same payload of the js
$result = array_reduce($data, function($res, $item){
$category = $item['category'];
$existing = $res[$category] ?? [];
$existing[] = ['value' => $item['id'], 'desc' => $item['subCategory']];
$res[$category] = $existing;
return $res;
}, []);
CodePudding user response:
As you seem to get your data from an SQL DB with PHP, your request can do the job without needing to loop anything with PHP or JS.
Can you try something like this?
$select = $conn->prepare(
"SELECT
DISTINCT category,
id AS subkategoris_value,
subcategory AS subkategoris_desc
FROM sometable"
);
$select->execute([]);
$result = $select->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_GROUP);
Here, replace sometable with the name of your table and $conn with your connection to MySQL DB.
Your output will be directly as expected.