combine and merge array in laravel - php

while merging array i got many isseus.
i used array_merge and array_combine in laravl but no success
array:4 [▼
"resident_id" => array:19 [▼
2 => "2"
1841 => "1841"
]
"community_id" => array:19 [▼
2 => "25"
1841 => "25"
1843 => "25"
]
"out_of_community" => array:5 [▼
2 =>
"2020-09-25"
1841 =>
"2020-09-25"
"
]
i want
resident_id community_id out_of_community
2 25 2020-09-25
1841 25 2020-09-25
please help me to solve it.
i did
$arr = $request->all();
$a = array_merge($arr);

I'm not sure if array_merge is the way to go. Looks like you are trying to transpose the data in a tabular format identified by the keys/ids in each of the sub arrays. Here is one approach that might work for you:
$keyCodes = array_keys($array['resident_id']); //get the keys to use when constructing the transposed array. $array is your data array
$dataToTabularFormat = [];
collect($keyCodes)->each(function($keyCode) use (&$dataToTabularFormat, $array) {
collect($array)->each(
function($item, $key) use($keyCode, &$dataToTabularFormat ) {
$dataToTabularFormat[$keyCode][$key] = $item[$keyCode] ;
}
);
});
Now, you can use $dataToTabularFormat to populate the table. In your blade view, you can do something like this:
#foreach($dataToTabularFormat as $item)
{{ $item['resident_id' }} {{ $item['community_id' }} {{ $item['out_of_community']}}
#endforeach

Related

convert array of arrays into comma separated list with unique values - PHP

I have an array that looks like below:
$var[] = ^ array:4 [▼
0 => array:1 [▼
0 => "apple"
]
1 => array:1 [▼
0 => "apple"
1 => "grape"
]
2 => array:1 [▼
0 => "orange"
]
3 => array:1 [▼
0 => "banana"
]
]
Is there a way to convert this array into comma separated list with unique values as below?
$var = "apple,grape,orange,banana"
I tried implode(', ',$var) but it's not working as expected. Any help pls?
Update: My sub-array may have more than 1 element. It's dynamic.
This produces the results given the expected input. Basically array_column get's the first item from each item of the array (0 based). Then array_unique on that will simply get the values without duplicates.
$arr = [
['apple'],
['apple'],
['banana'],
['pie'],
];
print_r(array_unique(array_column($arr, 0)));
EDIT: since there might be more than one item in the inner arrays, there's no shame in doing a non one-liner solution:
$result = [];
foreach ($arr as $row) {
foreach ($row as $item) {
if (array_search($item, $result) === false) {
$result[] = $item;
}
}
}
print_r($result);
There's also a one-liner solution:
$result= array_unique(call_user_func_array('array_merge', $arr));
cf. https://stackoverflow.com/a/14972714/13720553

How to get multiple arrays from an array in php?

I have he next array looks like:
array:50 [▼
0 => array:39 [▶]
1 => array:39 [▶]
2 => array:39 [▶]
]
So I want to get arrays with a value in common, for example:
array:39 [▼
"id" => 121
"user" => 368
]
array:39 [▼
"id" => 121
"user" => 3687
]
array:39 [▼
"id" => 500
"user" => 452
]
I want to get the two arrays with the attribute
id 121, I was trying to looping the array with foreach looks like:
foreach ($info as $val){
foreach($info as $f ){
if($f["id"]==$val["id"]){
//get the multiple arrays
}
}
}
So, I can't get all the arrays, some idea to how can do that?
I'd use a Collection.
collect your array of arrays:
$collection = collect([
[
"id" => 121
"user" => 368
],
[
"id" => 121
"user" => 3687
],
[
"id" => 500
"user" => 452
]
]);
Use the where method to filter based on a specific key's value:
$filtered = $collection->where('id', 121);
$filtered->all();
/*
[
['id' => '121', 'user' => 368],
['id' => '121', 'user' => 3687],
]
*/
Other where-like methods are available. Be sure to read through all of the documentation on Collections, it's full of great examples!
If you're now convinced that you should use Collections for everything, check out Adam Wathan's awesome book (and other resources): Refactoring to Collections (not free)

Laravel 5.8+get array of columns and rows from query

Relatively new to Laravel and trying to create a REST api that will have as a response a json that is split between rows and cols of a query
So, the code used to generate the json is:
$r = array(
'cols' => array_keys(get_object_vars(Dd_hr::take(2)->get())),
'rows' => Dd_hr::take(2)->get()
);
return response()->json($r, 201);
Basically, the json should look something like:
{"cols":[{"id", "user_name"}],"rows":[{"710206","user"}]}
But in fact it looks like:
{"cols":[],"rows":[{"id":"710206","user_name":"user"}]}
Could someone help me to solve this issue?
The result of dd(Dd_hr::take(2)->get()->toArray()):
array:2 [▼
0 => array:27 [▼
"rn" => "1"
"id" => "710206"
"user_name" => "user"
]
1 => array:27 [▼
"rn" => "2"
"id" => "710207"
"user_name" => "user"
]
]
Didn't find a way to do this properly so here goes the good old array_map.
This doesn't remove the "rn" key. If you want to chose the keys in the select you can, it'll even make creating the JSON easier since you'll already have the 'cols'.
$res_array = Dd_hr::take(2)->get()->toArray();
$cols = array_keys($res_array[0]);
$rows = array_map(function($row){
return array_values($row);
}, $res_array);
return response()->json(array('cols'=>$cols, 'rows'=>$rows), 201);
This returns :
"{"cols":["rn","id","user_name"],"row":[["1","710206","user"],["2","710207","user"]]}"

Laravel Loop Through Multidimesional Array

I am trying to loop through a multidimensional array in my view.
the array (I am passing $mailchimp from my controller to my view) is:
array:19 [▼
"id" => "f3200e9cc5a900bb7c075103b871232f0"
"email_address" => "john.doe#discworld.com"
"unique_email_id" => "xalasd"
"email_type" => "html"
"status" => "subscribed"
"merge_fields" => array:2 [▼
"FNAME" => "John"
"LNAME" => "Doe"
]
"stats" => array:2 [▶]
"ip_signup" => ""
"timestamp_signup" => ""
"ip_opt" => "93.212.91.32"
"timestamp_opt" => "2016-10-27T13:53:02+00:00"
"member_rating" => 2
"last_changed" => "2016-10-27T13:53:02+00:00"
"language" => ""
"vip" => false
"email_client" => ""
"location" => array:6 [▶]
"list_id" => "76980934492"
"_links" => array:8 [▶]
]
With this Code in my view:
#foreach($mailchimp as $user)
#foreach($user as $key => $value)
<ul>
<li>{{$value}}</li>
</ul>
#endforeach
#endforeach
An exception is thrown: Invalid argument supplied for foreach()
Can somebody tell me how to fix this ?
you are expecting for the value of each of the first array to also be an array. That is not the case, only some values from the first array is an array, so you must put a condition. You can use the is_array helper to see if the value from the first array is an actual array, if so, loop thru each one of those.
foreach($a as $b){
if(is_array($b)){
foreach($b as $c){
echo($c);
}
}
}
As mentioned by Carlos the main issue you're encountering is because you're trying to echo an array find his answer here.
Regarding your second issue Thanks Carlos. It tried you solution with this result: htmlentities() expects parameter 1 to be string, array given do you have any other code on that page, perhaps {{ Form::text('something', $array) }}

Loop through JSON Array and display results in table - Laravel 5.2

This question probably has been asked many times, but i cant get a solution.
I'm calling to a API like this:
public function getLeaderBoardArray($leaderBoardStats) {
$array = [];
$ex = $leaderBoardStats;
dd($ex);
return $array;
}
This is the result I get when I (DD) (Die-Dump it):
{#201 ▼
+"Start": 0
+"Count": 100
+"ResultCount": 100
+"Results": array:100 [▼
0 => {#199 ▼
+"Player": {#186 ▼
+"Gamertag": "Ferro2Clutch"
+"Xuid": null
}
+"Rank": 1
+"Score": {#195 ▶}
}
1 => {#188 ▶}
2 => {#200 ▶}
3 => {#203 ▶}
4 => {#206 ▶}
5 => {#209 ▶}
6 => {#212 ▶}
....... and so on till 100
How can a loop through this array and display Players Gamertag.
This i what I'm doing right now:
public function getLeaderBoardArray($leaderBoardStats) {
$array = [];
$array['Gamertag_1'] = $leaderBoardStats->Results[0]->Player->Gamertag;
$array['Csr_1'] = $leaderBoardStats->Results[0]->Score->Csr;
$array['Gamertag_2'] = $leaderBoardStats->Results[1]->Player->Gamertag;
$array['Csr_2'] = $leaderBoardStats->Results[1]->Score->Csr;
// and so on til 10....
return $array;
}
As you can see, this would be a pain to do till 100 for each leader-board.
Is there an easier method like somehow doing a for each loop?
You asked a very similar question yesterday and I'm going to give you a very similar answer today.
https://laravel.com/docs/5.2/collections
Use the map() Collection functionality to convert each item to a more digestable array.
$results = collect($leaderBoardStats->Results);
$gamers = $results->map(function($item, $key)
{
return [
'gamertag' => $item->Player->Gamertag,
'csr' => $item->Score->Csr,
]
});
This will give you an array that looks like ...
[
['gamertag' => "name", 'csr' => 11111],
['gamertag' => "name", 'csr' => 11111],
['gamertag' => "name", 'csr' => 11111],
['gamertag' => "name", 'csr' => 11111],
];
Then, in your view, you can do this to build a table.
#foreach ($gamers->all() as $gamer)
<tr>
<td>{{ $gamer['gamertag'] }}</td>
<td>{{ $gamer['csr'] }}</td>
</tr>
#endforeach
All it takes. Laravel Collections are probably one of the strongest aspects of the entire framework and are incredibly robust and well built. If you have an array-related question, chances are that documentation has a collection-related answer.
you can write a simple loop to iterate through your results. for example, I like using a foreach loop
$array = [];
foreach ($leaderBoardStats->Results as $stat) {
array[] = [
'gamer_tag' => $stat->Player->Gamertag,
'csr' => $stat->Score->Csr
];
}
return $array;
A better more advanced approach would be to map this so you don't have to create any extra arrays.
return array_map(function ($stat) {
return [
'gamer_tag' => $stat->Player->Gamertag,
'csr' => $stat->Score->Csr
];
}, $leaderBoardStats->Results);

Categories