foreach is losing values of an object - php

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! :)

Related

php unset not working with array of objects

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'];
});

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

Iterate through deeply nested array in PHP

I have data saved in JSON format (Prestashop) - I need to get to that data - which is deeply nested in arrays.
Here is the function:
public static function getAllCustomizedDatas($id_cart, $id_lang = null, $only_in_cart = true, $id_shop = null)
{
$datas = parent::getAllCustomizedDatas($id_cart, $id_lang, $only_in_cart, $id_shop);
var_dump($datas);
/*
* Iterate over $datas, you're looking for
* [id_product][id_product_attribute][id_address_delivery][id_customization][datas]
* Datas will contain an array of fields broken by their type. You can then decode
* the ones that need to be decoded and return the result:
*/
return $datas;
}
if I var_dump $datas I see this (I formatted this to make it a little easier for myself to read):
array(1) {
[8]=> array(1) {
[0]=> array(1) {
[0]=> array(2) {
[22]=> array(4) {
["datas"]=> array(1) {
[1]=> array(1) {
[0]=> array(9) {
["id_customization"]=> string(2) "22"
["id_address_delivery"]=> string(1) "0"
["id_product"]=> string(1) "8"
["id_customization_field"]=> string(1) "2"
["id_product_attribute"]=> string(1) "0"
["type"]=> string(1) "1"
["index"]=> string(1) "2"
["value"]=> string(615) "[[{"name":"item[1][line1]","customization":"asdf"},{"name":"item[1][line2]","customization":""},{"name":"item[1][line3]","customization":""},{"name":"item[1][line4]","customization":""},{"name":"item[1][line5]","customization":""},{"name":"item[1][line6]","customization":""},{"name":"item[1][line7]","customization":""}],[{"name":"item[2][line1]","customization":"asdf"},{"name":"item[2][line2]","customization":""},{"name":"item[2][line3]","customization":""},{"name":"item[2][line4]","customization":""},{"name":"item[2][line5]","customization":""},{"name":"item[2][line6]","customization":""},{"name":"item[2][line7]","customization":""}]]"
["name"]=> string(20) "Client Customization"
}
}
}
["quantity"]=> int(2)
["quantity_refunded"]=> int(0)
["quantity_returned"]=> int(0)
}
[23]=> array(4) {
["datas"]=> array(1) {
[1]=> array(1) {
[0]=> array(9) {
["id_customization"]=> string(2) "23"
["id_address_delivery"]=> string(1) "0"
["id_product"]=> string(1) "8"
["id_customization_field"]=> string(1) "2"
["id_product_attribute"]=> string(1) "0"
["type"]=> string(1) "1"
["index"]=> string(1) "2"
["value"]=> string(615) "[[{"name":"item[1][line1]","customization":"asdf"},{"name":"item[1][line2]","customization":""},{"name":"item[1][line3]","customization":""},{"name":"item[1][line4]","customization":""},{"name":"item[1][line5]","customization":""},{"name":"item[1][line6]","customization":""},{"name":"item[1][line7]","customization":""}],[{"name":"item[2][line1]","customization":"asdf"},{"name":"item[2][line2]","customization":""},{"name":"item[2][line3]","customization":""},{"name":"item[2][line4]","customization":""},{"name":"item[2][line5]","customization":""},{"name":"item[2][line6]","customization":""},{"name":"item[2][line7]","customization":""}]]"
["name"]=> string(20) "Client Customization"
}
}
}
["quantity"]=> int(2)
["quantity_refunded"]=> int(0)
["quantity_returned"]=> int(0)
}
}
}
}
}
What will be the easiest way to get to the ["value"] portion of the deeply nested array?
This has to be fairly dynamic because depending on the amount of items this user has - the amount of arrays will change. In this example, there are 2 there (each with 2 items in 'value'). A user could add 3 or 4 or 10 items if they wanted to. But I'm just trying to get to ['value'] and convert that JSON into HTML for the view this is getting passed to.
Bonus: Know of a way to easily iterate through the JSON data?
The JSON data looks like this:
[
[{
"name": "item[1][line1]",
"customization": "asdf"
}, {
"name": "item[1][line2]",
"customization": ""
}, {
"name": "item[1][line3]",
"customization": ""
}, {
"name": "item[1][line4]",
"customization": ""
}, {
"name": "item[1][line5]",
"customization": ""
}, {
"name": "item[1][line6]",
"customization": ""
}, {
"name": "item[1][line7]",
"customization": ""
}],
[{
"name": "item[2][line1]",
"customization": "asdf"
}, {
"name": "item[2][line2]",
"customization": ""
}, {
"name": "item[2][line3]",
"customization": ""
}, {
"name": "item[2][line4]",
"customization": ""
}, {
"name": "item[2][line5]",
"customization": ""
}, {
"name": "item[2][line6]",
"customization": ""
}, {
"name": "item[2][line7]",
"customization": ""
}]
]
I ended up just nesting a bunch of foreach statements until I had arrived at the array I wanted to. It was ugly, but functional.
Then I did json_decode across the JSON and iterated across it.
https://packagist.org/packages/ishworkh/multi-level-array-iterator
This might be helpful in iterating through deep nested array. And then use key or hierarchy information to filter out value needed for you.
Lets say this is your array
$array = [
[
[
[
[
"datas" => [
[
[
"id_customization" => "22",
"id_address_delivery" => "0",
"id_product" => "8",
"id_customization_field" => "2",
"id_product_attribute" => "0",
"type" => "1",
"index" => "2",
"value" => '[[{"name":"item[1][line1]","customization":"asdf"},{"name":"item[1][line2]","customization":""},{"name":"item[1][line3]","customization":""},{"name":"item[1][line4]","customization":""},{"name":"item[1][line5]","customization":""},{"name":"item[1][line6]","customization":""},{"name":"item[1][line7]","customization":""}],[{"name":"item[2][line1]","customization":"asdf"},{"name":"item[2][line2]","customization":""},{"name":"item[2][line3]","customization":""},{"name":"item[2][line4]","customization":""},{"name":"item[2][line5]","customization":""},{"name":"item[2][line6]","customization":""},{"name":"item[2][line7]","customization":""}]]',
"name" => "Client Customization",
],
],
],
"quantity" => 2,
"quantity_refunded" => 0,
"quantity_returned" => 0,
],
[
[
[
[
"id_customization" => "23",
"id_address_delivery" => "0",
"id_product" => "8",
"id_customization_field" => "2",
"id_product_attribute" => "0",
"type" => "1",
"index" => "2",
"value" => '[[{"name":"item[1][line1]","customization":"asdf"},{"name":"item[1][line2]","customization":""},{"name":"item[1][line3]","customization":""},{"name":"item[1][line4]","customization":""},{"name":"item[1][line5]","customization":""},{"name":"item[1][line6]","customization":""},{"name":"item[1][line7]","customization":""}],[{"name":"item[2][line1]","customization":"asdf"},{"name":"item[2][line2]","customization":""},{"name":"item[2][line3]","customization":""},{"name":"item[2][line4]","customization":""},{"name":"item[2][line5]","customization":""},{"name":"item[2][line6]","customization":""},{"name":"item[2][line7]","customization":""}]]',
"name" => "Client Customization",
],
],
],
"quantity" => 2,
"quantity_refunded" => 0,
"quantity_returned" => 0,
],
],
],
],
];
You could create a function like this, that uses multi-level-array-iterator's iterate method to go over all the nested array and
yield out found values.
/**
* #param array $nestedArray
*
* #return Generator
*/
function extractValuesFromArray(array $nestedArray):Generator
{
// $key is the local index key, which in this case should be 'value' we are looking to filter for
foreach(\ArrayIterator\ArrayIteratorFacade::iterate($nestedArray) as $key => $ArrayElement)
{
if ('value' === $key)
{
yield $ArrayElement->getValue();
}
}
}
var_dump(iterator_to_array(extractValuesFromArray($array)));
should give
array(2) {
[0]=>
string(643) "[[{"name":"item[1][line1]","customization":"asdf"},{"name":"item[1][line2]","customization":""},{"name":"item[1][line3]","customization":""},{"name":"item[1][line4]","customization":""},{"name":"item[1][line5]","customization":""},{"name":"item[1][line6]","customization":""},{"name":"item[1][line7]","customization":""}],[{"name":"item[2][line1]","customization":"asdf"},{"name":"item[2][line2]","customization":""},{"name":"item[2][line3]","customization":""},{"name":"item[2][line4]","customization":""},{"name":"item[2][line5]","customization":""},{"name":"item[2][line6]","customization":""},{"name":"item[2][line7]","customization":""}]]"
[1]=>
string(643) "[[{"name":"item[1][line1]","customization":"asdf"},{"name":"item[1][line2]","customization":""},{"name":"item[1][line3]","customization":""},{"name":"item[1][line4]","customization":""},{"name":"item[1][line5]","customization":""},{"name":"item[1][line6]","customization":""},{"name":"item[1][line7]","customization":""}],[{"name":"item[2][line1]","customization":"asdf"},{"name":"item[2][line2]","customization":""},{"name":"item[2][line3]","customization":""},{"name":"item[2][line4]","customization":""},{"name":"item[2][line5]","customization":""},{"name":"item[2][line6]","customization":""},{"name":"item[2][line7]","customization":""}]]"
}

group and/or rewrite an existing array

I'm using a database system for some kind of gaming competition where players can team up and participate in events. Right now players have their own database, then there is a database for teams (team id, name, join password, etc) and a database where I save which player (player name/id is in which team name/id). My database call gives me an array with team_name, username, etc. I wanted to group the users by a common team_name value which worked, but I'm not able to rewrite it according to my needs.
I want to build some kind of api for my personal use in C# application. There I want the output of my script to be json and I want to show all the teams with some details. Right now im using the following code:
$team_keys = array();
foreach ($team_data AS $k => $sub_array)
{
$this_team = $sub_array['team_name'];
$team_keys[$this_team][$k] = array('username' => $sub_array['username']);
}
echo json_encode($team_keys, JSON_PRETTY_PRINT);
This gives me an output like this:
{
"Team1": {
"0": {
"username": "player1"
},
"1": {
"username": "player2"
},
"22": {
"username": "player3"
}
},
"Team2": {
"2": {
"username": "player4"
},
"3": {
"username": "player5"
}, .....
}
But I want to achieve something like:
{
"team_name": "Team1",
"team_password": "secret",
"creation_timestamp": "123456789",
"players": [
"Player1",
"Player2",
"Player3"
]
}, ....
I tried tons of different approaches but I was simply not able to regroup and rewrite the array to my needs. Hopefully someone can help me out.
EDIT: $team_data looks like this (I'm using JOIN to join my user, teams, and team_member tables to get all the data together):
array(83) {
[0]=>
array(4) {
["username"]=>
string(8) "Player1"
["team_name"]=>
string(8) "Team1"
["team_password"]=>
string(7) "secret"
["team_id"]=>
string(1) "1"
}
[1]=>
array(4) {
["username"]=>
string(11) "Player2"
["team_name"]=>
string(8) "Team1"
["team_password"]=>
string(7) "secret"
["team_id"]=>
string(1) "1"
}
[2]=>
array(4) {
["username"]=>
string(8) "Player3"
["team_name"]=>
string(10) "Team2"
["team_password"]=>
string(6) "ultrasecret"
["team_id"]=>
string(1) "2"
},...
So Input was the following data
array(4) {
[0]=>
array(4) {
["team_name"]=>
string(5) "Team1"
["username"]=>
string(7) "player1"
["team_password"]=>
string(6) "secret"
["team_id"]=>
int(1)
}
[1]=>
array(4) {
["team_name"]=>
string(5) "Team1"
["username"]=>
string(7) "player2"
["team_password"]=>
string(6) "secret"
["team_id"]=>
int(1)
}
[2]=>
array(4) {
["team_name"]=>
string(5) "Team2"
["username"]=>
string(7) "player1"
["team_password"]=>
string(6) "secret"
["team_id"]=>
int(2)
}
[3]=>
array(4) {
["team_name"]=>
string(5) "Team2"
["username"]=>
string(7) "player2"
["team_password"]=>
string(6) "secret"
["team_id"]=>
int(2)
}
}
This is my code with my testset of $team_data
<?php
$team_data = array(array('team_name' => 'Team1', 'username' => 'player1', 'team_password' => 'secret', 'team_id' => 1)
,array('team_name' => 'Team1', 'username' => 'player2', 'team_password' => 'secret', 'team_id' => 1)
,array('team_name' => 'Team2', 'username' => 'player1', 'team_password' => 'secret', 'team_id' => 2)
,array('team_name' => 'Team2', 'username' => 'player2', 'team_password' => 'secret', 'team_id' => 2)
);
$team_keys = array();
foreach ($team_data AS $player_dara) {
if (!isset($team_keys[$player_dara['team_id']])) {
$team_keys[$player_dara['team_id']] = array();
$team_keys[$player_dara['team_id']]['team_name'] = $player_dara['team_name'];
$team_keys[$player_dara['team_id']]['team_id'] = $player_dara['team_id'];
$team_keys[$player_dara['team_id']]['secret'] = $player_dara['secret'];
$team_keys[$player_dara['team_id']]['players'] = array();
}
$team_keys[$player_dara['team_id']]['players'][] = $player_dara['username'];
}
echo json_encode(array_values($team_keys), JSON_PRETTY_PRINT);
Output
[
{
"team_name": "Team1",
"team_id": 1,
"secret": null,
"players": [
"player1",
"player2"
]
},
{
"team_name": "Team2",
"team_id": 2,
"secret": null,
"players": [
"player1",
"player2"
]
}
]

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