John Davidson

laravel - PHP array_column with foreach loop

0 comments
Message:


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.



My Answer:
>get();

I want to use array_column to get only the 'text' column values from the $records array and then loop through them using a foreach loop. How can I achieve this in Laravel?

Here's how you can achieve this:

php
// Get the 'text' column values using array_column
$textValues = array_column($records->toArray(), 'text');

// Loop through the 'text' column values using a foreach loop
foreach ($textValues as $text) {
// Do something with the $text value
echo $text . "
";
}


In this code snippet, we first convert the Eloquent collection $records to an array using the `toArray()` method. Then, we use the `array_column()` function to extract only the 'text' column values from the array. Finally, we loop through the extracted 'text' column values using a foreach loop and perform any desired operations on each value.

Rate this post

4 of 5 based on 4401 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us