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

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);

Related

combine and merge array in laravel

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

Get value by column name value

Ny array looks something like this:
Illuminate\Database\Eloquent\Collection {#2052 ▼
#items: array:3 [▼
0 => App\Models\NewsMeta {#2089 ▶}
1 => App\Models\NewsMeta {#2090 ▶}
2 => App\Models\NewsMeta {#2091 ▶}
]
}
If I open up the array 2:
#original: array:7 [▼
"id" => 17
"post_id" => 240231
"news_tag_id" => 5
"meta_name" => "_thumbnail_id"
"meta_value" => "240232"
"created_at" => "2020-08-06 22:34:06"
"updated_at" => "2020-08-06 22:34:06"
]
Now, I looking to get value "240232" given that I've 240231.
How do I search inside array of the object?
Something like: where post_id is 240231 get ts meta_value.
FYI: It's not eloquent or DB query.
Something like this should work:
$postId = 240231;
$metaValue = null;
foreach ($collection as $model) {
if ($model->post_id == $postId) {
$metaValue = $model->meta_value;
break;
}
}
echo $metaValue;
You could also use the collection's seach method:
$postId = 240231;
$metaValue = $collection->search(static function($model, $key) use($postId) {
if ($model->post_id == $postId) {
return $model->meta_value;
}
});
echo $metaValue;
You can use the collection firstWhere() method
$collection->firstWhere('post_id', '240231')['meta_value'] ?? null;
With the data you provided this should return 240232. In a dataset where there is no post_id = 240231 it would return null.

delete an array in list array in laravel session

I have a session to save cart info in laravel like this:
$item = [
'id' => 1,
'product_id' => 11
];
$item2 = [
'id' => 2,
'product_id' => 22
];
\Session::push('cart', $item);
\Session::push('cart', $item2);
Now I want delete an Item in array for $id=1:
foreach(\Session::get('cart') as $cart)
{
if($id==$cart['id'])
{
echo 'done';
\Session::forget('cart.' . $i);
}
$i++;
}
It print done but it can not delete that item in list.
what is my wrong?
also I try \Session::pull('card.id', $id);
EDIT
with dd(\Session::get('cart'))
array:4 [▼
2 => array:5 [▼
"id" => 1
"product_id" => "11"
]
3 => array:5 [▶]
4 => array:5 [▶]
5 => array:5 [▶]
]
So I try change the code to this:
foreach(\Session::get('cart') as $key->$cart)
{
if($id==$cart['id'])
{
\Session::forget('cart.' . $key);
}
}
But It can not delete too
I'm pretty sure that cart.{$id} is not a session key, as you're only explicitly setting cart, which is an array. This should work for you instead:
$id = 1; // set from request, etc.
$cartSession = session()->get("cart");
foreach($cartSession AS $index => $cart){
if($index == $id){
unset($cartSession[$index]);
}
}
session()->put("cart", $cartSession);
Essentially, you pull the session to a variable (array), loop that and unset where $index matches $id, then set the remaining array back as "cart".
Note: I'm using session() instead of \Session, which is just Facade vs global function; shouldn't make a difference on which you use, unless below a certain Laravel version (< 5.0 I believe)

Laravel swap the position in collection - multidimensional array

Following is the array in the collection:
array:1 [▼
"online" => array:2 [▼
"IS-003" => array:19 [▼
"product" => Product {#831 ▶}
"quantity" => 1
"payment-option" => "online"
]
"HA4" => array:19 [▼
"product" => Product {#822 ▶}
"quantity" => 1
"payment-option" => "online"
]
]
]
Whenever a user changes the payment-option, accordingly the above array should change.
For instance, if HA4['payment-option'] is changed from online to cod, then there should be 2 arrays in parent array.
Following is the array that I want as result.
array:2 [▼
"online" => array:1 [▼
"IS-003" => array:19 [▼
"product" => Product {#831 ▶}
"quantity" => 1
"payment-option" => "online"
]
]
"cod" => array:1 [▼
"HA4" => array:19 [▼
"product" => Product {#822 ▶}
"quantity" => 1
"payment-option" => "cod"
]
]
]
The thing that I have tried so far but couldn't get the desired result:
$paymentOptionCart = collect();
foreach ($cart as $paymentType => &$details) {
foreach ($details as $c => $p) {
if ($c == $code) {
$details[$c]['payment-option'] = $request->option;
$paymentOptionCart->put($paymentType, $details);
unset($details[$c]);
}
}
}
On executing the above code, nothing happens except the payment-option is updated to cod.
I know I am making a silly mistake somewhere, but I am unable to locate where and how.
Can anybody help me out?
This should do your task:
$array = [
"online" => [
"IS-003" => [
"quantity" => 1,
"payment-option" => "online"
],
"HA4" => [
"quantity" => 1,
"payment-option" => "online"
]
]
];
$code = "HA4";
$request_option = "cod";
foreach ($array as $paymentType => $details) {
foreach ($details as $c => $p) {
if ($c == $code) {
$array[$request_option][$c] = $p;
$array[$request_option][$c]["payment-option"] = $request_option;
unset($array[$paymentType][$c]);
}
}
}
unset($details[$c]) seems to be the problem... this punches out the element at index 0, at the end of the first iteration - and index 1 should then become index 0, which subsequently will not be accessible at index 1, during the next iteration of the loop. just run the loop until the exit condition is met and then unset them all, not during the loop... or loop backwards, in order to keep the indexes intact; this would unset the last one element at first and the loop would not exceed the array boundaries.
having two different payment options within a single online order is rather an unlikely example, haven't seen this yet. people might rather post two orders (which implies, not only the business logic is flawed, but the array structure has an unfortunate design, which requires such messing around).
xdebug is great for understanding what is happening. even if my answer might not answer the question in code one can copy & paste (that's not my job), xdebug will tell you exactly what the problem is.

Laravel - Decrease array size

Here is my code :
Controller :
$userOrder = $doctrineOrderRepository->getOrders(Auth::id());
Doctrine:
public function getUserOrders( $userId ) :array
{
$results = $this->_em->createQueryBuilder()
->select( 'o.restaurantId as rtId, o.oCount, o.oPrice ,
o.oCreated', 'o.oId' )
->from( $this->entityClass, 'o' )
->where( "o.userId = '{$userId}'" )
->andWhere( "o.orderItemCount > '0'" )
->andWhere( "o.orderTotalPrice > '0'" )
->getQuery()->getArrayResult();
return $results;
}
I get this array from my database Using Doctrine :
array:1 [▼
0 => array:5 [▼
"rtId" => 154
"oCount" => 2
"oPrice" => 33900
"oCreated" => DateTime {#677 ▶}
"oId" => 17428
]
]
I'm using this Doctrine method in different situations. In this case , I just use two item of all list : rtId , oCount
So , how to modify $userOrder to convert result array to this bellow array?
array:1 [▼
0 => array:2 [▼
"rtId" => 154
"oCount" => 2
]
]
foreach your $userOrder in controller and unset values like this
$newArr = array();
foreach($userOrder as $ar)
{
unset($ar['oPrice']);
unset($ar['oCreated']);
unset($ar['oId']);
$newArr[] = $ar;
}
dd($newArr);
you will get this result..
array:1 [▼
0 => array:2 [▼
"rtId" => 154
"oCount" => 2
]
]
If you are using Laravel, you can use the forever handy collection class. It has dozens of useful methods. In this case you could do:
$cleanedResults = collect($results)->map(function($item) {
return collect($item)->only(['rtId', 'oCount']);
})->toArray();

Categories