Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Display an ID based with multiple category ID with loop in PHP

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)

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; 

}, []);


about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda