Joining Multiple Arrays under some Logic - php

I have different arrays as follows:-
$reservations = ['reservationid' => '1', 'reservationid' => '2', 'reservationid' => '3']
$reservedrooms = ['reservationid'=> '1', 'roomno' => '1', 'reservationid' => '1', 'roomid'=>'2', 'reservationid' => '2', 'roomid'=>'3']
$guestdata = ['reservationid'=> '1', 'guestname' => 'Adam', 'reservationid' => '1', 'guestname'=>'Abraham', 'reservationid' => '2', 'guestname'=>'David']
How to join them so that they can be used as nested array with similar reservationids in CodeIgniter? I have also sent it to client side using Json and be depicted in JQuery Datatables. How to achieve it logically?
I have following code which is running on multiple tables
$this->db->from('hotelbrancheshasreservations');
$this->db->join('reservation', 'reservation.reservationid = hotelbrancheshasreservations.reservations_reservationsid');
$this->db->join('reservedrooms', 'reservedrooms.reservation_reservationid = hotelbrancheshasreservations.reservations_reservationsid');
$this->db->where( array('hotelbranches_hotelbranchesid'=>$branchid, 'status'=>$status));
$reservations = $this->db->get()->result_array();
I want result array as follows:-
$result = array (
"reservationid" => '1', 'rooms' => Array(
"roomno" => '1',
"roomno" => '2'), 'guests' => Array('guestid' => '1', 'guestname' => 'Adam', 'guestid' => '2', 'guestname' => 'David',) );

The following code is run in model class and then is returned back to controller. Then controller echos json object array to client side.
$this->$db->trans_start();
$this->$db->from('hotelbrancheshasreservations');
$this->$db->join('reservation', 'reservation.reservationid = hotelbrancheshasreservations.reservations_reservationsid');
$this->$db->join('reservedrooms', 'reservedrooms.reservation_reservationid = hotelbrancheshasreservations.reservations_reservationsid');
$this->$db->where( array('hotelbranches_hotelbranchesid'=>$branchid, 'status'=>$status));
$reservations = $this->$db->get()->result_array();
$this->$db->trans_complete();
return $reservations;
The above code returned following array after joining and in this solution problem is that if a reservation has more than one reserved rooms then that row is included in result set for multiple times and thats why i need to nest the reserved rooms in reservation array.
following is result set:
{"data":[{"hotelbrancheshasreservationsid":"18","hotelbranches_hotelbranchesid":"1","reservations_reservationsid":"KHAN2016Q221","status":"active","tblid":"19","reservationid":"KHAN2016Q221","startdate":"2016-05-16 11:59:00","enddate":"2016-05-21 11:59:00","duration":"","noofroom":"","reservationdate":"2016-05-22 01:41:32","guestarrivaldate":"0000-00-00 00:00:00","gestdeparturedate":"0000-00-00 00:00:00","totalreservedadults":"","totalreservedchilds":"","totalreservationcharges":"","createdby":"","createdon":"0000-00-00 00:00:00","lastmodifiedby":"","lastmodifiedon":"0000-00-00 00:00:00","reservedroomsid":"1","reservation_reservationid":"KHAN2016Q221","hotelrooms_hotelroomsid":"1"},{"hotelbrancheshasreservationsid":"145","hotelbranches_hotelbranchesid":"1","reservations_reservationsid":"KHAN2016Q3-34","status":"active","tblid":"146","reservationid":"KHAN2016Q3-34","startdate":"2016-07-24 00:22:31","enddate":"2016-07-25 00:22:37","duration":"1 days 6 seconds ","noofroom":"2","reservationdate":"2016-07-24 00:26:51","guestarrivaldate":"2016-07-24 00:26:30","gestdeparturedate":"2016-07-25 00:26:35","totalreservedadults":"2","totalreservedchilds":"2","totalreservationcharges":"1200","createdby":"1","createdon":"2016-07-24 00:23:05","lastmodifiedby":"","lastmodifiedon":"0000-00-00 00:00:00","reservedroomsid":"91","reservation_reservationid":"KHAN2016Q3-34","hotelrooms_hotelroomsid":"2"},{"hotelbrancheshasreservationsid":"145","hotelbranches_hotelbranchesid":"1","reservations_reservationsid":"KHAN2016Q3-34","status":"active","tblid":"146","reservationid":"KHAN2016Q3-34","startdate":"2016-07-24 00:22:31","enddate":"2016-07-25 00:22:37","duration":"1 days 6 seconds ","noofroom":"2","reservationdate":"2016-07-24 00:26:51","guestarrivaldate":"2016-07-24 00:26:30","gestdeparturedate":"2016-07-25 00:26:35","totalreservedadults":"2","totalreservedchilds":"2","totalreservationcharges":"1200","createdby":"1","createdon":"2016-07-24 00:23:15","lastmodifiedby":"","lastmodifiedon":"0000-00-00 00:00:00","reservedroomsid":"92","reservation_reservationid":"KHAN2016Q3-34","hotelrooms_hotelroomsid":"1"},{"hotelbrancheshasreservationsid":"146","hotelbranches_hotelbranchesid":"1","reservations_reservationsid":"KHAN2016Q3-35","status":"active","tblid":"147","reservationid":"KHAN2016Q3-35","startdate":"2016-07-25 22:05:36","enddate":"2016-07-26 22:05:41","duration":"1 days 5 seconds ","noofroom":"1","reservationdate":"2016-07-25 22:08:07","guestarrivaldate":"2016-07-25 22:07:53","gestdeparturedate":"2016-07-26 22:07:57","totalreservedadults":"1","totalreservedchilds":"","totalreservationcharges":"1500","createdby":"1","createdon":"2016-07-25 22:05:52","lastmodifiedby":"","lastmodifiedon":"0000-00-00 00:00:00","reservedroomsid":"93","reservation_reservationid":"KHAN2016Q3-35","hotelrooms_hotelroomsid":"4"},{"hotelbrancheshasreservationsid":"147","hotelbranches_hotelbranchesid":"1","reservations_reservationsid":"KHAN2016Q3-36","status":"active","tblid":"148","reservationid":"KHAN2016Q3-36","startdate":"2016-07-26 10:54:05","enddate":"2016-07-27 10:54:10","duration":"1 days 5 seconds ","noofroom":"1","reservationdate":"2016-07-26 10:56:15","guestarrivaldate":"2016-07-26 10:55:58","gestdeparturedate":"2016-07-27 10:56:03","totalreservedadults":"1","totalreservedchilds":"","totalreservationcharges":"700","createdby":"1","createdon":"2016-07-26 10:54:28","lastmodifiedby":"","lastmodifiedon":"0000-00-00 00:00:00","reservedroomsid":"94","reservation_reservationid":"KHAN2016Q3-36","hotelrooms_hotelroomsid":"3"}]}

Related

get a two dimensional array out of a query sql

i have a query like that:
$pd= DB::table("projects")
->orderBy("project_number", "asc")
->select('name' , "type")
->get()->keyBy('date_scheduled');;
and i get a array keyed By the date_scheduled which is fine, but the problem is date_scheduled is not unique so it overwrites the entries. So i need to get a two dimensional array with keyby date_scheduled like:
[
'date_1_of_date_scheduled' => [0 => '1', 1 => '4', 2 => '17']
'date_2_of_date_scheduled' => [0 => '15', 1 => '64', 2 => '1142']
'date_3_of_date_scheduled' => [0 => '25', 1 => '125', 2 => '66']
]
You can use groupBy() instead of keyBy(): https://laravel.com/docs/8.x/collections#method-groupby
$pd = DB::table("projects")
->orderBy("project_number", "asc")
->select('name' , "type")
->get()
->groupBy('date_scheduled');
You can use the laravel map function for the purpose
Try that:
$pd= DB::table("projects")
->orderBy("project_number", "asc")
->select('name' , "type")
->get()
->map(function ($item) {
return ['date_'.$item->date_scheduled.'_of_date_scheduled' => $item->YOUR_DESIRED_DATA] ;
}

PHP - how to randomly get something from array

how can i get something randomly from a array for example i have this array I want to grab one of those lines randomly how can I do that using PHP?
$quizes = array(
'3-1' => '2',
'4+4' => '8',
'7-5' => '2',
'4+2' => '6',
'9-3' => '6',
'1+2' => '3',
'9+9' => '18',
'3+2' => '5',
'2*3' => '6',
'5*3' => '15',
'6+6' => '12',
'3+4' => '7',
'7-4' => '3',
'6+2' => '8',
'3*2' => '6',
'7+6' => '13',
'1+1' => '2',
'4*4' => '16',
'10-3' => '7'
);
What i have tried
$rand_keys = array_rand($quizes, 2);
echo $quizes[$rand_keys[0]] . "\n";
echo $quizes[$rand_keys[1]] . "\n";
but this only returns results such as 2 7, 15 2, 3 2 and more
Please help thank you
You can randomize the array order and take the first element. The code would look like this:
shuffle($quizes);
Well, you are getting exactly what you are asking for - value that belongs to randomly chosen key.
To get key => value pair execute:
echo $rand_keys[0] . " => " . $quizes[$rand_keys[0]] . "\n";
Of course you can format output however you'd like to.
Each of the "rows" in your code is actually two parts: a key and its corresponding value. For example, in the first row '3-1' is the key and '2' is its value. The => operator indicates this relationship.
The array_rand function you used will return a random key (or set of keys, if you specify the second parameter) from your array.
$key = array_rand($quizes); // returns a random key e.g. '3-1'
Then you can use that key to get the corresponding value,
$value = $quizes[$key]; // returns the value that matches $key
There are various ways to output them from that point. If you want it to look kind of like it does in the code, you can use
echo "$key => $value";

Cakephp increasing update a column in the act

Good day!
I am running an update on two tables at once , but when I run the query cakephp is increasing the value of a column like a column with auto increment .
I have the following array:
$this->request->data = array(
'Model1' => array(
'id'=>'9',
'nome_fantasia' => 'Campos',
'razao_social' => 'Campos ',
'email' => 'testes#teste.com.br',
'responsavel_cpf' => '4456456465',
'ativo' => '1'
),
'Model2' => array(
(int) 0 => array(
'id' => '43',
'relacionamento_id' => '9',
'endereco' => 'Rua ******',
'numero' => '123',
'bairro' => 'bairro',
'cep' => '033888222'
)
)
);
And then the bass I have the update function:
$this->Modelo1->id = $this->request->data('Modelo1.id');
$this->Modelo1->saveAll( $this->request->data );
Ok , it does the Update in Model1 when it runs the update in Modelo2 it saves all the data but in the ' relacionamento_id ' instead of putting '9' as in this-> request- > data it is increasing with some ghost value. .. I realized that every time I run the query it will increase the number , for example
Attempt 1 = relacionamento_id = 50
Attempt 2 = relacionamento_id = 51
Attempt 3 = relacionamento_id = 52
Attempt 4 = relacionamento_id = 53
If I save both models separately it is right, but I would save direct .

How to turn sql result to multi-dimensional array dynamically?

Here is the query string.
$query = "SELECT t.id, t.assignee, t.owner,
d.code, d.status, d.target_completion_date,
d.target_extension_date, d.submission_date, d.approval_date,
d.revision_start_date, d.revision_completion_date, d.message,
ty.name, f.orig_name, f.new_name,
b.payment_date, b.discount, b.total_cost, b.amount_payed, b.edit_level,
b.billing_type, b.pages, b.words
FROM tasks t
INNER JOIN details d ON t.detail_id = d.id
INNER JOIN billing b ON t.billing_id = b.id
INNER JOIN TYPE ty ON d.document_type_id = ty.id
INNER JOIN files f ON t.file_id = f.id
WHERE t.assignee = 'argie1234'";
And this is the array i would like the query result to turn into.
$user = array('allTask'=>array(array('taskid' => 1,
'assignee'=>'argie1234',
'owner'=>'austral1000',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' =>'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
array('taskid' => 12,
'assignee'=>'argie1234',
'owner'=>'usaroberto',
'details' => array( 'code' => 'E',
'status'=>'TC',
'targetCompletionDateUTC'=>'1379401200',
'targetExtentionDateUTC'=>'1379401200',
'submissionDateUTC'=>'1379401200',
'approvalDateUTC'=>'1379401200',
'revisionStartDateUTC'=>'1379401200',
'revisionCompletionDateUTC'=>'1379401200',
'messageToEditor'=>'Please work on it asap.',
'documentType' => 'Thesis'),
'file' => array('orig_name' => 'originalname.docx',
'new_name' => 'newname.docx'),
'billing'=>array('paymentDate'=>'July 26,2013 12:40',
'discount' => '0',
'totalRevisionCharge' => '$20.00',
'totalAmountPayed' => '$20.00',
'revisionLevel' => '1',
'chargeType'=> '1',
'numPages' => '60',
'numWords' => '120,000' ) ),
'account' => array( 'username' => 'marooon55',
'emailadd' => 'marooon#yahoo.com',
'firstname' => 'Maroon',
'initial' => 'E',
'lastname' => 'Young',
'country' => 'Australia',
'gender' => 'M',
'password' =>'360e2801190744a2af74ef6cbfdb963078b59709',
'activationDate' => '2013-09-13 14:30:34') );
How can i create the above array? I sure know how to define multi dimensional array, regretfully though i am having difficulty creating this complex array dynamically. As a beginner i don't even know where to begin.
Here is an example that might help you out. Try starting with simple multi dimensional arrays, once you get a hold of it, you can move onto building complex ones. You will then find that the array you want to build is not really difficult than you initially thought it to be.
$mycomplexarray = array('key1' => array('val1', 'val2'),
'key2' => array('val3', 'val4' => array('val5', 'val6')
)
);
You could create the array just as you have here. I'm not gonna write the whole thing out, but something like this...
$result = $mysqli->query($query); // however you query the db is up to you.
$row = $result->fetch_assoc(); //same as query use your prefered method to fetch
$user = array('allTask'=>array(array('taskid' => $row['id'],
'assignee'=>$row['assignee'],
'owner'=>$row['owner'],
'details' => array( 'code' => $row['code'],
'status'=>$row['status'],
...etc, Hope this makes sense for you.
Set up a structure array first that defines which columns will be stored in a sub array like
$struc=array('Id'->0, 'assignee'->0, 'owner'->0,
'code'->'detail', 'status'->'detail', 'target_completion_date'->'detail',
'target_extension_date'->'detail', 'submission_date'->'detail', 'approval_date'->'detail',
'revision_start_date'->'detail', 'revision_completion_date'->'detail', 'message'->'detail',
'name'->'file', 'orig_name'->'file', 'new_name'->'file',
'payment_date'->'billing', 'discount'->'billing', 'total_cost'->'billing', 'amount_payed'->'billing', 'edit_level'->'billing', 'billing_type'->'billing', 'words');
In your while ($a=mysqli_fetch_assoc($res)) loop you can now use this structure to decide whether you want to store an element directly in your target array or whether you want to place it in the subarray named in this structure array. Like
$res=mysqli_query($con,$sql);
$arr=array();
while($a=mysqli_fetch_assoc($res)) {
// within result loop: $a is result from mysqli_fetch_assoc()
$ta=array(); // temp array ...
foreach ($a as $k => $v){
if ($struc[$k]) $ta[struc[$k]][$k]=$v;
else $ta[$k]=$v;
}
$arr[]=$ta; // add to target array
}
This is the complete code, no more is needed. It was typed up on my iPod, so it is NOT tested yet.
The generated array should be equivalent to your $user['allTask'] array.

cakephp: filtering fields from child table in find('all')

My question extends one posted previously CakePHP: Limit Fields associated with a model. I used this solution effectively for limiting the returned fields for the parent table with this call
$data = $this->SOP10100->find('all',
array('fields' => $this->SOP10100->defaultFields));
However, this method returns the filtered parent and unfiltered child fields. I have 131 child fields of which I only need 7. I have the same defaultFields array construct in the child table. How do I modify this call ( or create a new one) that will return the filtered fields for both parent and child models in the same array?
Here is the structure for the array for the parent table:
public $defaultFields = array(
'SOP10100.SOPNUMBE',
'SOP10100.INVODATE',
'SOP10100.DOCDATE',
'SOP10100.DOCAMNT',
'SOP10100.SUBTOTAL');
Your help is appreciated.
SCORE! Wow, solved two big problems in one day. I finally figured it out with loads of help from many resources:
$this->InvoiceHeader->Behaviors->attach('Containable');
$data = $this->InvoiceHeader->find('all', array(
'fields' => $this->InvoiceHeader->defaultFields,
'contain' => array(
'InvoiceDetail' => array(
'fields' => $this->InvoiceDetail->defaultFields))
)
);
returns my array data just like I want it:
array(
(int) 0 => array(
'InvoiceHeader' => array(
'SOPNUMBE' => 'SVC0202088 ',
'INVODATE' => '2012-04-17 00:00:00',
'DOCDATE' => '2012-04-17 00:00:00',
'DOCAMNT' => '.00000',
'SUBTOTAL' => '.00000'
),
'InvoiceDetail' => array(
(int) 0 => array(
'ITEMNMBR' => 'SERVICE ',
'QUANTITY' => '1.00000',
'UOFM' => 'EA ',
'UNITPRCE' => '.00000',
'TAXAMNT' => '.00000',
'CONTSTARTDTE' => '2012-04-17 00:00:00',
'CONTENDDTE' => '2012-04-30 00:00:00',
'SOPNUMBE' => 'SVC0202088 '
),

Categories