jeudi 12 novembre 2020

PHP array_column with foreach loop

I have a table from which i am fetching some columns

 $records=Table::select('id','text','type')->paginate(250)->toArray();
 $data=$records->['data'];

I am getting output as :-

array:250 [
  0 => array:4 [
    "id" => 1
    "text" => "text1"
    "type" => "A"
  ]
  1 => array:4 [
    "id" => 1
    "text" => "text2"
    "type" => "B"
  ]
  2 => array:4 [
    "id" => 1
    "text" => "text3"
    "type" => "C"
  ]
  3 => array:4 [
    "id" => 2
    "text" => "text4"
    "type" => "A"
  ]
  4 => array:4 [
    "id" => 2
    "text" => "text5"
    "type" => "B"
  ]
  5 => array:4 [
    "id" => 2
    "text" => "text6"
    "type" => "C"
  ]
  6 => array:4 [
    "id" => 3
    "text" => "text7"
    "type" => "A"
  ]
  7 => array:4 [
    "id" => 3
    "text" => "text8"
    "type" => "B"
  ]
  8 => array:4 [
    "id" => 3
    "text" => "text9"
    "type" => "C"
  ]....
]

I want to convert it into array of objects/array of arrays where results of same id should merge in such a way that value of "type" should be key and value of "text" as value. Below is a sample of expected result:-

array:20 [
{
"id" => 1
"A" => "text1"
"B"=>"text2"
"C"=>"text3"
}
{
"id" => 2
"A" => "text4"
"B"=>"text5"
"C"=>"text6"
}
{
"id" => 3
"A" => "text7"
"B"=>"text8"
"C"=>"text9"
}...
]

I have tried using array_column.

$sortedRecords = array_column($data, 'text','type');

Using array_column, i am able to convert value of "type" as key and "text" value as its value. But i am not able getting how to display id also and how to loop for each distinct id as it is displaying result of only last id.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire