php unset not working with array of objects - php

i have an array of objects received from mongodb i have a custom soft delete feature, for which i have to loop through the objects find the key deleted_at and unset it from the array this is how my array looks like if i dump it
object(MongoDB\Model\BSONArray)#41 (1) {
[
"storage": "ArrayObject":private
]=>
array(15) {
[
0
]=>
object(MongoDB\Model\BSONDocument)#26 (1) {
[
"storage": "ArrayObject":private
]=>
array(4) {
[
"name"
]=>
string(18) "BCasdaadaadadasdas"
[
"email"
]=>
string(20) "hank-zakroff#mac.com"
[
"mobileNo"
]=>
string(11) "11-22-33-44"
[
"deleted_at"
]=>
string(19) "2019-08-21 10:08:43"
}
}
[
1
]=>
object(MongoDB\Model\BSONDocument)#27 (1) {
[
"storage": "ArrayObject":private
]=>
array(4) {
[
"name"
]=>
string(9) "ADasdBSDS"
[
"email"
]=>
string(23) "haasdnk-zakroff#mac.com"
[
"mobileNo"
]=>
string(11) "03338142535"
[
"deleted_at"
]=>
string(19) "2019-08-21 11:08:17"
}
}
[
2
]=>
object(MongoDB\Model\BSONDocument)#28 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(12) "Hank Zakroff"
[
"email"
]=>
string(20) "hank-zakroff#mac.com"
[
"mobileNo"
]=>
string(11) "03244424280"
}
}
[
3
]=>
object(MongoDB\Model\BSONDocument)#29 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(12) "Hank Zakroff"
[
"email"
]=>
string(20) "hank-zakroff#mac.com"
[
"mobileNo"
]=>
string(11) "03244424281"
}
}
[
4
]=>
object(MongoDB\Model\BSONDocument)#30 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(9) "Kate Bell"
[
"email"
]=>
string(17) "kate-bell#mac.com"
[
"mobileNo"
]=>
string(13) "(555)564-8583"
}
}
[
5
]=>
object(MongoDB\Model\BSONDocument)#31 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(9) "Kate Bell"
[
"email"
]=>
string(17) "kate-bell#mac.com"
[
"mobileNo"
]=>
string(13) "(415)555-3695"
}
}
[
6
]=>
object(MongoDB\Model\BSONDocument)#32 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(14) "Daniel Higgins"
[
"email"
]=>
string(17) "d-higgins#mac.com"
[
"mobileNo"
]=>
string(12) "555-478-7672"
}
}
[
7
]=>
object(MongoDB\Model\BSONDocument)#33 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(14) "Daniel Higgins"
[
"email"
]=>
string(17) "d-higgins#mac.com"
[
"mobileNo"
]=>
string(13) "(408)555-5270"
}
}
[
8
]=>
object(MongoDB\Model\BSONDocument)#34 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(14) "Daniel Higgins"
[
"email"
]=>
string(17) "d-higgins#mac.com"
[
"mobileNo"
]=>
string(13) "(408)555-3514"
}
}
[
9
]=>
object(MongoDB\Model\BSONDocument)#35 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(14) "John Appleseed"
[
"email"
]=>
string(22) "John-Appleseed#mac.com"
[
"mobileNo"
]=>
string(12) "888-555-5512"
}
}
[
10
]=>
object(MongoDB\Model\BSONDocument)#36 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(14) "John Appleseed"
[
"email"
]=>
string(22) "John-Appleseed#mac.com"
[
"mobileNo"
]=>
string(12) "888-555-1212"
}
}
[
11
]=>
object(MongoDB\Model\BSONDocument)#37 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(9) "Anna Haro"
[
"email"
]=>
string(17) "anna-haro#mac.com"
[
"mobileNo"
]=>
string(12) "555-522-8243"
}
}
[
12
]=>
object(MongoDB\Model\BSONDocument)#38 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(12) "Hank Zakroff"
[
"email"
]=>
string(20) "hank-zakroff#mac.com"
[
"mobileNo"
]=>
string(13) "(555)766-4823"
}
}
[
13
]=>
object(MongoDB\Model\BSONDocument)#39 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(12) "Hank Zakroff"
[
"email"
]=>
string(20) "hank-zakroff#mac.com"
[
"mobileNo"
]=>
string(13) "(707)555-1854"
}
}
[
14
]=>
object(MongoDB\Model\BSONDocument)#40 (1) {
[
"storage": "ArrayObject":private
]=>
array(3) {
[
"name"
]=>
string(12) "David Taylor"
[
"email"
]=>
string(20) "hank-zakroff#mac.com"
[
"mobileNo"
]=>
string(12) "555-610-6679"
}
}
}
}
for unsetting the index i did what i normally do in arrays
foreach ($is_exist['contacts'] as $key => $value) {
if(#$value['deleted_at']){
unset($is_exist['contacts'][$key]);
}
}
now i have matching objects at key 0 and 1 but the problem is it unsets the key 0 but not key 1 i have tried many combinations like
//pass by reference doesnot work at all
foreach ($is_exist['contacts'] as $key => &$value) {
if(#$value['deleted_at']){
unset($value);
}
}
i even tried
reset($is_exist['contacts']);
just after my unset condition but that doesn't work as well
it's strange , this doesn't happen normally any idea why this is happening?

... the problem is it unsets the key 0 but not key 1
It's generally not good practice to mutate an array in-place while iterating its items.
You're bound to run into this problem as the internal array pointer (PHP versions < 7) is destroyed in the unset operation.
You can make a copy of the original array and iterate over that copy while modifying the original array or better, make a filtered copy with undeleted documents.
I prefer the later approach to be straight-forward and clear on the intent. e.g.
$contacts = $is_exist['contacts'];
$active_contacts = [];
foreach ($contacts as $key => &$value) {
if(is_null(#$value['deleted_at']))
{
$active_contacts[] = #$value;
}
}
$is_exist['contacts'] = $active_contacts;

Filter in the db query may be better than your php code.
If you want to filter it with your php code, use a new array to store the filter item instead of doing inplace modificaiton.
$result = [];
foreach($array as $v){
if(!$v['deleted_at']){
$result[] = $v;
}
}
or
$result = array_filter($array,function($v){
return !$v['deleted_at'];
});

Related

Php empty result

The result I get in the query I run with Mysql is the result I want. But when I send the same values ​​in my php code (even though the query is the same), it returns null.The query is a bit long but I thought I could do it. Trying a few things to improve myself
SELECT user_pictures.picture,users.username,
star,quest1.answer1,quest2.answer2,
quest3.answer3,quest4.answer4,quest5.answer5,
votes.created_at
FROM votes
LEFT JOIN user_pictures ON votes.voted_image_id=user_pictures.ID
LEFT JOIN users ON votes.voting_id=users.ID
LEFT JOIN quest1 ON votes.q1=quest1.ID
LEFT JOIN quest2 ON votes.q2=quest2.ID
LEFT JOIN quest3 ON votes.q3=quest3.ID
LEFT JOIN quest4 ON votes.q4=quest4.ID
LEFT JOIN quest5 ON votes.q5=quest5.ID
WHERE voted_id = "123456"
AND voting_id = "123"
how can i get the same result in my php code
<?php
require_once('connection.php');
if($_GET){
$voted_id = $_GET['voted_id'];
$voting_id = $_GET['voting_id'];
$sql = "SELECT user_pictures.picture,users.username,
star,quest1.answer1,quest2.answer2,
quest3.answer3,quest4.answer4,quest5.answer5,
votes.created_at
FROM votes
LEFT JOIN user_pictures ON votes.voted_image_id=user_pictures.ID
LEFT JOIN users ON votes.voting_id=users.ID
LEFT JOIN quest1 ON votes.q1=quest1.ID
LEFT JOIN quest2 ON votes.q2=quest2.ID
LEFT JOIN quest3 ON votes.q3=quest3.ID
LEFT JOIN quest4 ON votes.q4=quest4.ID
LEFT JOIN quest5 ON votes.q5=quest5.ID
WHERE voted_id = ?
AND voting_id = ? ";
$stmt = $connect->prepare($sql);
$stmt->bind_param("ii", $voted_id, $voting_id);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
header('Content-Type:application/json;charset=urf-8');
echo json_encode($data);
}
?>
When I use var_dump($data) and var_dump($_GET) I can get the result I got in sql
array(2) {
[
"voting_id"
]=>
string(6) "123456"
[
"voted_id"
]=>
string(3) "123"
}
array(2) {
[
0
]=>
array(9) {
[
"picture"
]=>
string(4) "pic2"
[
"username"
]=>
string(18) "Cihangir Karabulut"
[
"star"
]=>
string(1) "2"
[
"answer1"
]=>
string(6) "Patron"
[
"answer2"
]=>
string(5) "?tici"
[
"answer3"
]=>
string(4) "Sexy"
[
"answer4"
]=>
string(9) "Karadeniz"
[
"answer5"
]=>
string(5) "50-59"
[
"created_at"
]=>
string(19) "2023-01-24 14:16:24"
}
[
1
]=>
array(9) {
[
"picture"
]=>
string(4) "pic2"
[
"username"
]=>
string(18) "Cihangir Karabulut"
[
"star"
]=>
string(1) "4"
[
"answer1"
]=>
string(7) "�?renci"
[
"answer2"
]=>
string(9) "G�venilir"
[
"answer3"
]=>
string(10) "At H?rs?z?"
[
"answer4"
]=>
string(6) "Do?ulu"
[
"answer5"
]=>
string(5) "25-29"
[
"created_at"
]=>
string(19) "2023-01-24 19:20:28"
}
}

foreach is losing values of an object

So this a completely stupid beginner question but I spent so much time just investigating whats going on and I have absolutely no more ideas.
I'm trying to get private values of an object called "Cell" out of an CellLineRepository. The getters are working, they're getting used at a different place.
This is how my foreach looks:
$all_cell_lines = CellLineRepository::findAll();
$allcells = [];
foreach ($all_cell_lines as $cell) {
$allcells[] = [
"CellID" => $cell->getId(),
"iPSC-ID" => $cell->getIpscId(),
"Lab-ID" => $cell->getLabId(),
"altID" => $cell->getAltId(),
"project" => $cell->getProject()
];
var_dump($allcells);
}
A var_dump() of $all_cell_lines looks good, but I'm losing "iPSC-ID" and "Lab-ID".
object(CellLine)#9 (79) {
[
"id": "CellLine":private
]=>
string(1) "1"
[
"created_date": "CellLine":private
]=>
string(10) "2019-05-22"
[
"created_by": "CellLine":private
]=>
string(3) "314"
[
"last_modified_date": "CellLine":private
]=>
string(10) "2019-11-22"
[
"last_modified_by": "CellLine":private
]=>
string(3) "301"
[
"tab_type": "CellLine":private
]=>
string(8) "internal"
[
"lab_id": "CellLine":private
]=>
string(5) "xxx"
[
"alt_id": "CellLine":private
]=>
string(7) "xxx"
[
"provider": "CellLine":private
]=>
string(36) "xxx"
A var_dump() of $allcells looks like this:
array(1) {
[
0
]=>
array(5) {
[
"CellID"
]=>
string(1) "1"
[
"iPSC-ID"
]=>
string(0) ""
[
"Lab-ID"
]=>
string(0) ""
[
"altID"
]=>
string(7) "xxx"
[
"project"
]=>
string(3) "xxx"
}
}
Does someone have a clue?
try this way around please
foreach ($all_cell_lines as $cell) {
$allcells[] = [
"CellID" => $cell->id,
"iPSC-ID" => $cell->ipsc_id,
"Lab-ID" => $cell->lab_id,
"altID" => $cell->alt_id,
"project" => $cell->project
];
var_dump($allcells);
}
try to fetch using your field name in the database
Wow, so this was crazy. I used modules of other devs but they made their permission check in the ORM not in frontend.
This is what I found:
public function getLabId() {
return perissionCheck('lab_id') ? $this->lab_id : '';
}
Thanks anyways! :)

PHP foreach loop repeated entries

I need help in order to manipulate a multidimensional array during PHP foreach loop. I have the array below:
$sports = [
[
"id" => "soccer",
"name" => "Football",
"categories" => [
[
"id" => "s1",
"name" => "category 1",
"sportID" => "soccer"
],
[
"id" => "s2",
"name" => "category 2",
"sportID" => "soccer"
],
],
"img" => "/test.png"
],
[
"id" => "tennis",
"name" => "Tennis",
"categories" => [
[
"id" => "t1",
"name" => "category 1",
"sportID" => "tennis"
],
[ "id" => "t2",
"name" => "category 2",
"sportID" => "tennis"
],
],
"img" => "/test.png"
],
];
I have the below foreach in order to take all the sports with the corresponding categories for every sport,
foreach($sports as $s){
$categories = $s['categories'];
foreach($categories as $c){
$cats[] = [
"id" => $c['id'],
"name" => $c['name'],
"sportID" => $s['id'],
];
}
$allCategories[] = $cats;
$data[] = [
"id" => $s['id'],
"name" => $s['name'],
"categories" => $cats,
"img" => $s['img'],
];
$output[] = $data;
}
but the output is not what I expected; instead, I am getting repeated results like the one below:
array(2) {
[0]=>
array(1) {
[0]=>
array(4) {
["id"]=>
string(8) "soccer"
["name"]=>
string(8) "Football"
["categories"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(2) "s1"
["name"]=>
string(10) "category 1"
["sportID"]=>
string(8) "soccer"
}
[1]=>
array(3) {
["id"]=>
string(2) "s2"
["name"]=>
string(10) "category 2"
["sportID"]=>
string(8) "soccer"
}
}
["img"]=>
string(9) "/test.png"
}
}
[1]=>
array(2) {
[0]=>
array(4) {
["id"]=>
string(8) "soccer"
["name"]=>
string(8) "Football"
["categories"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(2) "s1"
["name"]=>
string(10) "category 1"
["sportID"]=>
string(8) "soccer"
}
[1]=>
array(3) {
["id"]=>
string(2) "s2"
["name"]=>
string(10) "category 2"
["sportID"]=>
string(8) "soccer"
}
}
["img"]=>
string(9) "/test.png"
}
[1]=>
array(4) {
["id"]=>
string(10) "tennis"
["name"]=>
string(8) "Tennis"
["categories"]=>
array(4) {
[0]=>
array(3) {
["id"]=>
string(2) "s-1"
["name"]=>
string(10) "category 1"
["sportID"]=>
string(8) "soccer"
}
[1]=>
array(3) {
["id"]=>
string(2) "s2"
["name"]=>
string(10) "category 2"
["sportID"]=>
string(8) "soccer"
}
[2]=>
array(3) {
["id"]=>
string(2) "t1"
["name"]=>
string(10) "category 1"
["sportID"]=>
string(10) "tennis"
}
[3]=>
array(3) {
["id"]=>
string(2) "t2"
["name"]=>
string(10) "category 2"
["sportID"]=>
string(10) "tennis"
}
}
["img"]=>
string(9) "/test.png"
}
}
}
As you can imagine this is not the correct output, as in the categories of the tennis you can see the categories of the soccer also.
How can I correct my foreach loop in order to get the correct output?
You forget to reset $cats and $data arrays.
<?php
$sports = [
[
"id" => "soccer",
"name" => "Football",
"categories" => [
[
"id" => "s1",
"name" => "category 1",
"sportID" => "soccer"
],
[
"id" => "s2",
"name" => "category 2",
"sportID" => "soccer"
],
],
"img" => "/test.png"
],
[
"id" => "tennis",
"name" => "Tennis",
"categories" => [
[
"id" => "t1",
"name" => "category 1",
"sportID" => "tennis"
],
[ "id" => "t2",
"name" => "category 2",
"sportID" => "tennis"
],
],
"img" => "/test.png"
],
];
foreach($sports as $s){
$categories = $s['categories'];
# before inner loop we need to reset both arrays
$cats = [];
$data = [];
foreach($categories as $c){
$cats[] = [
"id" => $c['id'],
"name" => $c['name'],
"sportID" => $s['id'],
];
}
$allCategories[] = $cats;
$data[] = [
"id" => $s['id'],
"name" => $s['name'],
"categories" => $cats,
"img" => $s['img'],
];
$output[] = $data;
}
echo '<PRE>';
print_r($output);

Laravel Many to Many query relationship with where clause

Problem
I want to make use of eloquent rather than relying in joins
Queries
$relationship = DB::table('tournament_user')
->join('tournaments','tournament_user.tournament_id' , '=', 'tournaments.id')
->join('users', 'tournament_user.user_id', '=', 'users.id')
->select('tournament_user.user_id','tournament_user.tournament_id')
->where('tournament_user.user_id','=',$request->user()->id)
->get();
This query returns list of all tournaments id for a loggedin user.
How can I avoid joins?
I tried this : $relations = User::with('tournaments')->where('id',$request->user()->id)->get();
It returns only one row. whereas there are 3 tournaments that belong to user with id = 2.
I want to simply convert the above Joins query to use eloquent model.
User Model
public function tournaments()
{
return $this->belongsToMany('App\Tournament', 'tournament_user','tournament_id','user_id');
}
Tournament Model
public function users()
{
return $this->belongsToMany('App\User','tournament_user','tournament_id','user_id');
}
Var_Dump
object(Illuminate\Database\Eloquent\Collection)#350 (1){
[
"items":protected
] => array(1) {
[
0
] => object(App\User)#345 (23) {
[
"table":protected
] => string(5) "users" [
"fillable":protected
] => array(5) {
[
0
] => string(4) "name" [
1
] => string(5) "email" [
2
] => string(3) "dob" [
3
] => string(6) "gender" [
4
] => string(8) "password"
} [
"hidden":protected
] => array(2) {
[
0
] => string(8) "password" [
1
] => string(14) "remember_token"
} [
"connection":protected
] => NULL [
"primaryKey":protected
] => string(2) "id" [
"perPage":protected
] => int(15) [
"incrementing"
] => bool(true) [
"timestamps"
] => bool(true) [
"attributes":protected
] => array(12) {
[
"id"
] => int(2) [
"name"
] => string(4) "john" [
"email"
] => string(14) "john#gmail.com" [
"role"
] => string(4) "user" [
"gender"
] => string(4) "male" [
"status"
] => string(6) "active" [
"dob"
] => string(10) "2001-01-01" [
"password"
] => string(60) "$2y$10$QCtSuNroLftEm.xFLiAbheCt32dSp24rXfn9aJX8pvfbVNVMKyZ.6" [
"remember_token"
] => string(60) "3CPQZ1GSFjTV4qBkCoxt30fOSMrKHsPCkgeMb3uJwKz2nyKUqsDABizIVssH" [
"created_at"
] => string(19) "2016-03-16 10:49:29 " [" updated_at"
] => string(19) "2016-07-23 10:49:35 " [" image"
] => string(13) "/img/user.png"
} [
"original":protected
] => array(12) {
[
"id"
] => int(2) [
"name"
] => string(4) "john" [
"email"
] => string(14) "john#gmail.com" [
"role"
] => string(4) "user" [
"gender"
] => string(4) "male" [
"status"
] => string(6) "active" [
"dob"
] => string(10) "2001-01-01" [
"password"
] => string(60) "$2y$10$QCtSuNroLftEm.xFLiAbheCt32dSp24rXfn9aJX8pvfbVNVMKyZ.6" [
"remember_token"
] => string(60) "3CPQZ1GSFjTV4qBkCoxt30fOSMrKHsPCkgeMb3uJwKz2nyKUqsDABizIVssH" [
"created_at"
] => string(19) "2016-03-16 10:49:29 " [" updated_at"
] => string(19) "2016-07-23 10:49:35 " [" image"
]=> string(13) "/img/user.png"
}[
"relations":protected
]=> array(1){
[
"tournaments"
]=> object(Illuminate\Database\Eloquent\Collection)#353 (1){
[
"items":protected
] => array(1) {
[
0
] => object(App\Tournament)#352 (23) {
[
"table":protected
] => string(11) "tournaments" [
"fillable":protected
] => array(7) {
[
0
] => string(6) "t_name" [
1
] => string(6) "t_desc" [
2
] => string(6) "t_club" [
3
] => string(10) "t_location" [
4
] => string(6) "t_date" [
5
] => string(11) "t_starttime" [
6
] => string(9) "t_endtime"
} [
"connection":protected
] => NULL [
"primaryKey":protected
] => string(2) "id" [
"perPage":protected
] => int(15) [
"incrementing"
] => bool(true) [
"timestamps"
] => bool(true) [
"attributes":protected
] => array(12) {
[
"id"
] => int(2) [
"t_name"
] => string(22) "Flag Stroke Play Event" [
"t_desc"
] => string(499) "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters,
as opposed to using 'Content here. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen book." [
"t_club"
] => string(21) "Hermitage golf course" [
"t_location"
] => string(7) "Sharjah" [
"t_date"
] => string(10) "2016-07-20" [
"t_starttime"
] => string(8) "10:00:00 " [" t_endtime"
] => string(8) "01:00:00 " [" lat"
] => float(25.2) [
"lng"
] => float(55.27) [
"created_at"
] => string(19) "2016-02-22 16:00:00 " [" updated_at"
] => string(19) "2016-06-07 12:36:06 " } [" original":protected
]=> array(14){
[
"id"
] => int(2) [
"t_name"
] => string(22) "Flag Stroke Play Event" [
"t_desc"
] => string(499) "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters,
as opposed to using 'Content here. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type specimen book." [
"t_club"
] => string(21) "Hermitage golf course" [
"t_location"
] => string(7) "Sharjah" [
"t_date"
] => string(10) "2016-07-20" [
"t_starttime"
] => string(8) "10:00:00 " [" t_endtime"
]=> string(8) "01:00:00" ["lat"
]=> float(25.2)[
"lng"
]=> float(55.27)[
"created_at"
]=> string(19) "2016-02-22 16:00:00" ["updated_at"
]=> string(19) "2016-06-07 12:36:06" ["pivot_tournament_id"
]=> int(2)[
"pivot_user_id"
]=> int(2)
}[
"relations":protected
]=> array(1){
[
"pivot"
]=> object(Illuminate\Database\Eloquent\Relations\Pivot)#351 (26){
[
"parent":protected
]=> object(App\User)#331 (23){
[
"table":protected
]=> string(5) "users"[
"fillable":protected
]=> array(5){
[
0
]=> string(4) "name"[
1
]=> string(5) "email"[
2
]=> string(3) "dob"[
3
]=> string(6) "gender"[
4
]=> string(8) "password"
}[
"hidden":protected
]=> array(2){
[
0
]=> string(8) "password"[
1
]=> string(14) "remember_token"
}[
"connection":protected
]=> NULL[
"primaryKey":protected
]=> string(2) "id"[
"perPage":protected
]=> int(15)[
"incrementing"
]=> bool(true)[
"timestamps"
]=> bool(true)[
"attributes":protected
]=> array(0){
}[
"original":protected
]=> array(0){
}[
"relations":protected
]=> array(0){
}[
"visible":protected
]=> array(0){
}[
"appends":protected
]=> array(0){
}[
"guarded":protected
]=> array(1){
[
0
]=> string(1) "*"
}[
"dates":protected
]=> array(0){
}[
"dateFormat":protected
]=> NULL[
"casts":protected
]=> array(0){
}[
"touches":protected
]=> array(0){
}[
"observables":protected
]=> array(0){
}[
"with":protected
]=> array(0){
}[
"morphClass":protected
]=> NULL[
"exists"
]=> bool(false)[
"wasRecentlyCreated"
]=> bool(false)
}[
"foreignKey":protected
]=> string(13) "tournament_id"[
"otherKey":protected
]=> string(7) "user_id"[
"guarded":protected
]=> array(0){
}[
"connection":protected
]=> NULL[
"table":protected
]=> string(15) "tournament_user"[
"primaryKey":protected
]=> string(2) "id"[
"perPage":protected
]=> int(15)[
"incrementing"
]=> bool(true)[
"timestamps"
]=> bool(false)[
"attributes":protected
]=> array(2){
[
"tournament_id"
]=> int(2)[
"user_id"
]=> int(2)
}[
"original":protected
]=> array(2){
[
"tournament_id"
]=> int(2)[
"user_id"
]=> int(2)
}[
"relations":protected
]=> array(0){
}[
"hidden":protected
]=> array(0){
}[
"visible":protected
]=> array(0){
}[
"appends":protected
]=> array(0){
}[
"fillable":protected
]=> array(0){
}[
"dates":protected
]=> array(0){
}[
"dateFormat":protected
]=> NULL[
"casts":protected
]=> array(0){
}[
"touches":protected
]=> array(0){
}[
"observables":protected
]=> array(0){
}[
"with":protected
]=> array(0){
}[
"morphClass":protected
]=> NULL[
"exists"
]=> bool(true)[
"wasRecentlyCreated"
]=> bool(false)
}
}[
"hidden":protected
]=> array(0){
}[
"visible":protected
]=> array(0){
}[
"appends":protected
]=> array(0){
}[
"guarded":protected
]=> array(1){
[
0
]=> string(1) "*"
}[
"dates":protected
]=> array(0){
}[
"dateFormat":protected
]=> NULL[
"casts":protected
]=> array(0){
}[
"touches":protected
]=> array(0){
}[
"observables":protected
]=> array(0){
}[
"with":protected
]=> array(0){
}[
"morphClass":protected
]=> NULL[
"exists"
]=> bool(true)[
"wasRecentlyCreated"
]=> bool(false)
}
}
}
}[
"visible":protected
]=> array(0){
}[
"appends":protected
]=> array(0){
}[
"guarded":protected
]=> array(1){
[
0
]=> string(1) "*"
}[
"dates":protected
]=> array(0){
}[
"dateFormat":protected
]=> NULL[
"casts":protected
]=> array(0){
}[
"touches":protected
]=> array(0){
}[
"observables":protected
]=> array(0){
}[
"with":protected
]=> array(0){
}[
"morphClass":protected
]=> NULL[
"exists"
]=> bool(true)[
"wasRecentlyCreated"
]=> bool(false)
}
}
}
It looks correct for a many-to-many relationship.
The following should give you all the users and then for each user it returns the tournaments using eager loading on the tournaments relationship.
$users = User::with('tournaments')->get();
foreach ($users as $user) {
foreach ($user->tournaments as $tournament) {
// Do what you want todo with the tournament
}
}
Then for your case it will return a single user with its tournaments.
$user = User::with('tournaments')->where('id', $request->user()->id)->get();
foreach ($user->tournaments as $tournament) {
// Do what you want todo with the tournament
}
I guess your relationships in model is wrong.
Your Relationship
public function tournaments()
{
return $this->belongsToMany('App\Tournament', 'tournament_user','tournament_id','user_id');
}
But as per Laravel Documentation,
The third argument is the foreign key name of the model on which you
are defining the relationship, while the fourth argument is the
foreign key name of the model that you are joining to:
Which mean your relationship in User Model should be like
public function tournaments()
{
return $this->belongsToMany('App\Tournament', 'tournament_user', 'user_id', 'tournament_id');
}

Map two arrays key and value to create json object in php

Hi guys I'm trying to map key with values in PHP to create JSON object, can someone help please.
My keys array:
[
"ID",
"NAME",
"PRICE",
"TYPE"
]
My values array:
[
[
"1",
"Chicken Royal",
"25",
"Sandwich"
],
[
"2",
"Beef Whopper",
"30",
"Burger"
],
[
"3",
"Beef Royal",
"30",
"Burger"
]
]
What I'm looking for is:
[
"ID":"1",
"NAME":"Chicken Royal",
"PRICE":"25",
"TYPE":"Sandwich"
]
I've used this function
$result = array_map( function($k,$v) { return array('column' => $k,'value' => $v); }, array_keys($columnNames),$values);
With array_combine you can creates an array by using one array for keys and another for its values.
$keys = [
"ID",
"NAME",
"PRICE",
"TYPE"
];
$values = [
[
"1",
"Chicken Royal",
"25",
"Sandwich"
],
[
"2",
"Beef Whopper",
"30",
"Burger"
],
[
"3",
"Beef Royal",
"30",
"Burger"
]
];
$results = array_map(function($values) use ($keys) {
return array_combine($keys, $values);
}, $values);
var_dump($results);
Output:
array(3) {
[0]=>
array(4) {
["ID"]=>
string(1) "1"
["NAME"]=>
string(13) "Chicken Royal"
["PRICE"]=>
string(2) "25"
["TYPE"]=>
string(8) "Sandwich"
}
[1]=>
array(4) {
["ID"]=>
string(1) "2"
["NAME"]=>
string(12) "Beef Whopper"
["PRICE"]=>
string(2) "30"
["TYPE"]=>
string(6) "Burger"
}
[2]=>
array(4) {
["ID"]=>
string(1) "3"
["NAME"]=>
string(10) "Beef Royal"
["PRICE"]=>
string(2) "30"
["TYPE"]=>
string(6) "Burger"
}
}

Categories