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";
Related
I have a multidimensional array as follows, which is a PHP array of shoe sizes and their conversions...
$size_array = array(
"M"=>array(
'6'=> array('uk'=>'6','eu'=>'39.5','us'=>'7'),
'6H'=> array('uk'=>'6.5','eu'=>'40','us'=>'7.5'),
'7'=> array('uk'=>'7','eu'=>'40.5','us'=>'8'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'8.5'),
'8'=> array('uk'=>'8','eu'=>'42','us'=>'9'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'9.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'10'),
'9H'=> array('uk'=>'9.5','eu'=>'44','us'=>'10.5'),
'10'=> array('uk'=>'10','eu'=>'44.5','us'=>'11'),
'10H'=> array('uk'=>'10.5','eu'=>'45','us'=>'11.5'),
'11'=> array('uk'=>'11','eu'=>'46','us'=>'12'),
'11H'=> array('uk'=>'11.5','eu'=>'46.5','us'=>'12.5'),
'12'=> array('uk'=>'12','eu'=>'47','us'=>'13'),
'12H'=> array('uk'=>'12.5','eu'=>'48','us'=>'13.5'),
'13'=> array('uk'=>'13','eu'=>'48.5','us'=>'14')
),
"F"=>array(
'3'=> array('uk'=>'3','eu'=>'35.5','us'=>'5'),
'3H'=> array('uk'=>'3.5','eu'=>'36','us'=>'5.5'),
'4'=> array('uk'=>'4','eu'=>'37','us'=>'6'),
'4H'=> array('uk'=>'4.5','eu'=>'37.5','us'=>'6.5'),
'5'=> array('uk'=>'5','eu'=>'38','us'=>'7'),
'5H'=> array('uk'=>'5.5','eu'=>'38.5','us'=>'7.5'),
'6'=> array('uk'=>'6','eu'=>'39','us'=>'8'),
'6H'=> array('uk'=>'6.5','eu'=>'39.5','us'=>'8.5'),
'7'=> array('uk'=>'7','eu'=>'40','us'=>'9'),
'7H'=> array('uk'=>'7.5','eu'=>'41','us'=>'9.5'),
'8'=> array('uk'=>'8','eu'=>'41.5','us'=>'10'),
'8H'=> array('uk'=>'8.5','eu'=>'42.5','us'=>'10.5'),
'9'=> array('uk'=>'9','eu'=>'43','us'=>'11'),
'9H'=> array('uk'=>'9.5','eu'=>'43.5','us'=>'11.5'),
'10'=> array('uk'=>'10','eu'=>'44','us'=>'12')
)
);
The array is part of a function that returns the conversions based on a supplied size and gender (i.e. SizeConvert('M','6') returns Array ([uk] => 6, [eu] => 39.5,[us] => 7)).
I want to extend the function to allow the passing of a value which will return the array results with any .5 values replaced with ½ (or ½) (i.e. SizeConvert('M','6','Y') returns Array ([uk] => 6, [eu] => 39½,[us] => 7))
How do I make str_replace (or a more appropriate command) iterate over the array and replace the values?
I've tried something like str_replace(".5", "½", $size_array) but I guess that's not working as it's only looking at the initial array, not the sub-arrays.
You are trying to apply this to a multidimensional array without real reason. If you have your SizeConvert function ready and returning a one dimensional array, simply apply the transformation before returning the value:
function SizeConvert(/* other parameters */, bool $convertOneHalf) {
$match = ... // your code to find the match
return $convertOneHalf
? str_replace('.5', '½', $match)
: $match;
}
Based on the boolean value of the parameter that dictates whether the conversion should be applied, we either return the modified or the unmodified result through the ternary.
Do not overthink it and use a for loop to loop through all the elements in the array and use an if...else... to check for 0.5
if($array[index]=="0.5") {
$array[index]="½";
} else {
$array[index]=str_replace(".5", "½", $array[index]);
}
I coded up a simple code, it's not exactly the answer to your question but u can use the logic behind it. The code below will change all the 0.5 in the array to 1⁄2 but since u already acquire the data, there is no need to have so much nested-loop, just 1 level of the loop to loop through all ur elements in your array is enough.
<?php
$size_array = array(
"M" => array(
'6' => array(
'uk' => '6',
'eu' => '39.5',
'us' => '7'
) ,
'6H' => array(
'uk' => '6.5',
'eu' => '40',
'us' => '7.5'
) ,
'7' => array(
'uk' => '7',
'eu' => '40.5',
'us' => '8'
)
) ,
"F" => array(
'3' => array(
'uk' => '3',
'eu' => '35.5',
'us' => '5'
) ,
'3H' => array(
'uk' => '3.5',
'eu' => '36',
'us' => '5.5'
) ,
'4' => array(
'uk' => '4',
'eu' => '37',
'us' => '6'
)
)
);
foreach ($size_array as $firstLevel)
{
foreach ($firstLevel as $secondLevel)
{
foreach ($secondLevelas $values)
{
if ($values== "0.5")
{
echo $values= "½";
}
else
{
echo $values= str_replace(".5", "½", $values);
}
}
}
}
?>
I have questions model in laravel that has a database structure like this:
question_id | is_active
------------+-----------
1 | Y
2 | Y
3 | N
... | ...
I have an input in form of an array that i want to validate with questions model, this array will contain key that act as the question_id and the value as the question answer, that looks like this:
$QnAs = [
'1' => '3',
'2' => '5',
'4' => '1',
'6' => '4',
'7' => '2',
'8' => '0',
]
The validation system will required all the Active (is_active == 'Y') questions that present in the array as question_id as the key of array to represent it and the value of each array is 1, 2, 3, or 4.
I can achieve that by looping through every question that active like this:
$collections = Questions::where('is_active','Y')->get();
foreach($collections as $collection){
if(!array_key_exists($collection->question_id,$QnAs)){
return false; // doesn't find the question id in array key input
} elseif(!in_array($QnAs[$collection->$question_id],['1','2','3','4'])){
return false; // input value for this array does not match with required value
}
}
the problem with this code is , when i process 15k++ data it will take a long time too process because it has to loop through every model collection , is there any other approach that can simplify the code and the process ?
Your code wont work . Beacause return will immediately end the execution of current function. So the checking will be done only with the first value in collections and it will return the result based on the first element in the array $collections.
you can change the code as following :
$collections = Questions::where('is_active','Y')->get();
$result = true;
foreach($collections as $collection)
{
if(!array_key_exists($collection->question_id,$QnAs))
{
$result = false; // doesn't find the question id in array key input
}
}
return $result;
The above code will work
You can research more for greater performance
The problem is you are getting all of the active questions,
so the point is to limit the datas,
Firstly, add composite index on question_id and is_active
$table->index(['question_id', 'is_active']);
And try this code:
$QnAs = [
'1' => '3',
'2' => '5',
'4' => '1',
'6' => '4',
'7' => '2',
'8' => '0',
];
// filter elements allowed:
$valid_QnAs = array();
foreach($QnAs as $k => $v) {
if (in_array($v, [1,2,3,4])) {
$valid_QnAs[$k] = $v;
}
}
$not_in_active = Questions::where('is_active','Y')
->whereNotIn('question_id', array_keys($valid_QnAs))
->exists();
if ($not_in_active) return false;
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"}]}
echo $this->Form->input('quantity', array('options' => array('1','2','3','4')));
I have this code to input the values 1,2,3 or 4 into the quantity field in my database.
If a user selects 1 it inputs 0, 2 inputs 1 etc.
If the code is
echo $this->Form->input('quantity');
The user can input what they like and guess what...
It works. What am I doing wrong?
I think you're trying to implement a drop-down box. I think you can try this:
$options = array('1' => '1', '2' => '2', '3' => '3', '4' => '4');
echo $this->Form->input('quantity', array('options' => $options, 'default' => '1'));
this will create a select drop down box.
For detail please see here.
I have an array of data which contains associative array rows and I would like to sort them by price,date etc. This cannot be done via SQL as these values are not in a database - I simply have a large array with the following example data:
$data[0] = array(
'id' => '2',
'price' => '400.00',
'date' => '2012-05-21',
),
$data[1] = array(
'id' => '4',
'price' => '660.00',
'date' => '2012-02-21',
),
$data[2] = array(
'id' => '8',
'price' => '690.00',
'date' => '2012-01-21',
)
etc..................
How can I sort this variable based on a select box such as sort by price ASC/DESC and date ASC/DESC
Sorry if this is simple - I am just so used to doing it via SQL that my mind has gone blank in this case.
I think you may modify this function:
http://php.net/manual/en/function.sort.php#104464
You should use usort and define a function which sorts based on the key you want.
Check out http://www.php.net/manual/en/function.usort.php examples 2 and 4.
Below sample code will sort it by id.
$capitals = array(
array(
'id' => '2',
'price' => '400.00',
'date' => '2012-05-21',
),
array(
'id' => '1',
'price' => '660.00',
'date' => '2012-02-21',
),
array(
'id' => '0',
'price' => '690.00',
'date' => '2012-01-21',
)
);
function cmp($a, $b)
{
return strcmp($a["id"], $b["id"]);
}
usort($capitals, "cmp");
print_r($capitals);
Use usort:
function sortBySubKey(&$array, $key)
{
return usort($array, create_function('$a,$b', 'if ($a["'.$key.'"] == $b["'.$key.'"]) return 0; return ($a["'.$key.'"] < $b["'.$key.'"]) ? -1 : 1;'));
}
You should make sure that your array holds valid values in the sense of this arithmetical comparision (<), eg. you should probably pass date as a unix timestamp for this, price as a float and so on...