Looping through PHP array shows invalid Response - php

I have created a function in PHP that mainly index files from a txt file here is the function that was supposed to do the job
public function getPlayingItem()
{
$playData = [];
$startTimes = [];
for($i=0; $i < count($this->playListFiles); $i++){
$item = $this->playListFiles[$i];
if(empty($item)){
unset($this->playListFiles[$i]);
continue;
}
$tmp = explode(',', $item);
$playData[$i]['startTime'] = array_pop($tmp);
$startTimes[$i] = $playData[$i]['startTime'];
$playData[$i]['name'] = implode(',',$tmp);
}
array_multisort($startTimes, SORT_ASC, $playData);
for($i=0; $i < count($playData); $i++){
if (strtotime($playData[$i]['startTime']) >= time()){
break;
}
}
$info = $this->get_mp3($playData[$i-1]['name'], true, false);
$tmp = explode(DS,$playData[$i-1]['name']);
$name = array_pop($tmp);
$playing = ['number'=>($i-1),'path'=>$playData[$i-1]['name'],'name'=>$name,'duration'=>$info['data']['time'],'startTime'=>$playData[$i-1]['startTime']];
$info = $this->get_mp3($playData[$i]['name'], true, false);
$tmp = explode(DS,$playData[$i]['name']);
$name = array_pop($tmp);
$next = ['number'=>$i,'path'=>$playData[$i]['name'],'name'=>$name,'duration'=>$info['data']['time'],'startTime'=>$playData[$i]['startTime']];
$output = ['playing'=>$playing, 'next'=>$next];
return $output;
}
Here is the txt file
E:\xampp\htdocs\radioclass\files\2021-02-23 22.47.04.mp3,19:10:00
E:\xampp\htdocs\radioclass\files\2021-03-15 19.39.25.mp3,19:10:39
E:\xampp\htdocs\radioclass\files\2021-05-15 19.05.13.mp3,19:10:43
E:\xampp\htdocs\radioclass\files\2021-07-14 23.04.50.mp3,19:11:03
E:\xampp\htdocs\radioclass\files\2021-08-31 11.55.38.mp3,19:11:05
E:\xampp\htdocs\radioclass\files\2021-08-31 11.56.23.mp3,19:11:09
E:\xampp\htdocs\radioclass\files\2021-09-03 23.47.38#ssr.mp3,19:12:19
E:\xampp\htdocs\radioclass\files\frmu.mp3,19:12:23
E:\xampp\htdocs\radioclass\files\frmun.mp3,19:12:26
The response:
{"playing":{"number":8,"path":"E:\\xampp\\htdocs\\radioclass\\files\\frmun.mp3","name":"frmun.mp3","duration":"00:10","startTime":"19:12:26"},"next":{"number":9,"path":null,"name":"","duration":null,"startTime":null}}
**Now the problem is that first of all it should start from 0 and end at 10 and the second thing is that it shows the path, name, duration, of the second line as null any help will be greatly appreciated because I'm a begginer **

Related

How to retrieve all media entries in Kaltura, beyond the 10k mark?

I am using the php5.3 SDK: https://github.com/kaltura/KalturaGeneratedAPIClientsPHP53
We have 90k media entries, but I can only got 20k entries. The following code is straight forward. Could anyone help me out?
// Main entry point
public function mywrite(Route $route, Console $console)
{
// Max records is 500, the range cannot be too big.
$range = 3600 * 24;
$this->__mywrite($route, $console, $range);
}
// Count how many objects we can get
// $veryStartDate == 1446173087, sep 2015
// $maxDate == 1526469375, may 2018
public function __mywrite($route, $console, $range) {
$configObj = $this->readMyWriteHistoryConfigFile();
$lastProcessObj = $this->readMyWriteLastProcessFile();
//
$veryStartDate = $configObj->veryStartDate;
$maxDate = $configObj->maxDate;
// Set start Date
$startDate = $veryStartDate;
$endDate = $startDate + $range;
//
$totalCount = 0;
while($startDate <= $maxDate) {
$objs = $this->listMediaByLastPlay($startDate, $endDate);
$totalCount += count($objs);
echo "\n$startDate - $endDate:\n";
echo "\n". count($objs). "\n";
$startDate = $endDate + 1;
$endDate = $endDate + $range;
} // end while loop
// we get like 25k records, but we have 90k records....
echo "\ncount: $totalCount\n";
}
// we call the client and get records by start last play date and end last play date
public function listMediaByLastPlay($startDate, $endDate) {
// Page size
$pageSize = 1000;
// Client with admin
$client = $this->getClient(\KalturaSessionType::ADMIN);
// media
$mediaObj = $client->media;
// Set a range to pull, order by last played at
$filter = new \KalturaMediaEntryFilter();
$filter->lastPlayedAtGreaterThanOrEqual = $startDate;
$filter->lastPlayedAtLessThanOrEqual = $endDate;
$filter->orderBy = '+lastPlayedAt';
// We still want more records
$pager = new \KalturaFilterPager();
$pager->pageSize = $pageSize;
// now list.....
$arr = $mediaObj->listAction($filter, $pager)->objects;
$buf = array();
foreach($arr as $k => $v) {
$t = array();
$t['dataUrl'] = $v->dataUrl;
$t['flavorParamsIds'] = $v->flavorParamsIds;
$t['plays'] = $v->plays;
$t['views'] = $v->views;
$t['lastPlayedAt'] = $v->lastPlayedAt;
$buf[] = $t;
}
return $buf;
}
You're iterating on the first page of each response, there might be more that one page.
The kaltura ListResponse has a totalCount property.
so you code should something like:
$pager = new \KalturaFilterPager();
$pageIndex = 1;
$entriesGot = 0;
$buf = array();
do
{
$pager->pageSize = $pageSize;
$pager->pageIndex = $pageIndex++;
// now list.....
$response = $mediaObj->listAction($filter, $pager);
$arr = $response->objects;
$entriesGot += count($arr);
foreach($arr as $k => $v) {
$t = array();
$t['dataUrl'] = $v->dataUrl;
$t['flavorParamsIds'] = $v->flavorParamsIds;
$t['plays'] = $v->plays;
$t['views'] = $v->views;
$t['lastPlayedAt'] = $v->lastPlayedAt;
$buf[] = $t;
}
}while($entriesGot < $response->totalCount);

Why my Cakephp web service query takes lot of time to return data?

I've got a web service which takes around 15 secs to return JSON response to front-end.My code looks like this:
Controller code:
public function getDetailReport($data){
$user_id = $data->user_id;
$test_id = $data->test_id;
$result_obj = new TestSetDetailResultTable();
$data_array = $result_obj->getDetailReportByUser($user_id, $test_id);
if($data_array['status'] == 1) {
echo $this->successMessage('successfully Executed',$data_array['record']);
} else {
echo $this->failMessage($data_array['error'],$data_array['message']);
}
exit;
}
Model code:
public function getDetailReportByUser($user_id,$test_id) {
$data_array = Array();
$subject_array = Array();
$answer_array = Array();
$topper_array = Array();
$percentile_array = Array();
$max_marks = 0;
$perc = 0;
$hrs = 0;
$mint = 0;
$sec = 0;
$query = new AppQuery();
$query->callProcedure('getSummaryResult',array($test_id,$user_id));
$row_list = $this->loadRowList($query);
if(count($row_list) > 0) {
$max_marks = $row_list[0]->maximum_marks;
$perc = $row_list[0]->percentage;
$query->callProcedure('getCompletedTestTime',array($user_id,$test_id));
$row_time = $this->loadRowList($query);
$query->callProcedure('getAllUserPerTest',array($test_id));
$row_user = $this->loadRowList($query);
if(count($row_time)> 0 && count($row_user) > 0) {
foreach ($row_list as $list) {
$item['test_name'] = $list->test_name;
$item['total_question'] = $list->total_question;
$item['right_answer'] = $list->right_answer;
$item['wrong_answer'] = $list->wrong_answer;
$item['question_attempted'] = $list->question_attempted;
$item['question_not_attempted'] = $list->question_not_attempted;
$item['positive_marks'] = $list->positive_marks;
$item['negative_marks'] = $list->negative_marks;
$item['obtaine'] = $list->obtaine;
$item['maximum_test_time'] = $list->maximum_test_time;
$item['maximum_marks'] = $list->maximum_marks;
$item['test_date'] = $list->test_date;
$number = floatval($list->obtaine)* 100 / intval($list->maximum_marks);
$item['percentage'] = number_format($number, 2, '.', ''); // upto 2 decimal places
$data_array['detail'] = $item;
}
$tmp = Array();
$hrs = $row_time[0]->spent_hours;
$mint = $row_time[0]->spent_minute;
$sec = $row_time[0]->spent_second;
$completed_minute = $row_time[0]->compeleted_minute;
$completed_second = $row_time[0]->compeleted_second;
if($completed_second < 0) {
$completed_second = -1 * $completed_second; // only removing - sign
}
$tmp = $this->calculateTime($hrs, $mint, $sec);
$tmp['compeleted_minute'] = $completed_minute;
$tmp['compeleted_second'] = $completed_second;
$data_array['time'] = $tmp;
foreach ($row_user as $list) {
$tem['total_user'] = $list->total_user;
$data_array['users'] = $tem;
}
// Now get The subject wise Result
$temp = Array();
$query->callProcedure('getTestResult',array($test_id,$user_id));
$subject_result = $this->loadRowList($query);
foreach ($subject_result as $res) {
$temp['subject_name']= $res->subject_name;
$temp['marks_obtained'] = $res->obtaine;
$temp['total_question'] = $res->total_question;
$temp['question_attempted'] = $res->question_attempted;
$temp['wrong_answer'] = $res->wrong_answer;
// $temp['total_spent_hours'] = $res->total_spent_hours;
// $temp['total_spent_minute'] = $res->total_spent_minute;
// $temp['total_spent_second'] = $res->total_spent_second;
$time_arr2 = $this->calculateTime($res->total_spent_hours, $res->total_spent_minute, $res->total_spent_second);
$temp['total_spent_hours'] = $time_arr2['hours'];
$temp['total_spent_minute'] = $time_arr2['minute'];;
$temp['total_spent_second'] = $time_arr2['second'];
$temp['max_marks'] = intval($res->total_question) * intval($res->positive_marks);
$subject_array[] = $temp;
}
$data_array['subject_result'] = $subject_array;
//>>>>>>>>>>> Now get Answer of Question with Time spent>>>>>>>>>>
$temp = Array();
$query->callProcedure('getAnswerwithTime',array($test_id,$user_id));
$answer_list = $this->loadRowList($query);
foreach ($answer_list as $res) {
$temp['question']= utf8_encode($res->question);
$temp['user_answer']= $res->user_answer;
$temp['correct_answer'] = $res->correct_answer;
$temp['spent_hours'] = $res->spent_hours;
$temp['spent_minute'] = $res->spent_minute;
$temp['spent_second'] = $res->spent_second;
$temp['obtaine'] = $res->obtaine;
$answer_array[] = $temp;
}
$data_array['answer_with_time'] = $answer_array;
/*>>>>>>>>End>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Topper result for Comparing>>>>>>>>>>>>>>>>*/
$temp = Array();
$query->callProcedure('getTopperResult',array($test_id));
$top_arr = $this->loadRowList($query);
foreach ($top_arr as $top) {
$temp['user_name'] = $top->user_name;
$temp['test_name'] = $top->test_name;
$temp['total_question'] = $top->total_question;
$temp['right_answer'] = $top->right_answer;
$temp['wrong_answer'] = $top->wrong_answer;
$temp['question_attempted'] = $top->question_attempted;
$temp['question_not_attempted'] = $top->question_not_attempted;
$temp['positive_marks'] = $top->positive_marks;
$temp['negative_marks'] = $top->negative_marks;
$temp['maximum_marks'] = $top->maximum_marks;
$temp['obtaine'] = $top->obtaine;
$temp['percentage'] = $top->percentage;
$temp['maximum_test_time'] = $top->maximum_test_time;
$temp['test_date'] = $top->test_date;
$timer = $this->calculateTime( $top->spent_hours, $top->spent_minute, $top->spent_second);
$temp['spent_hours'] = $timer['hours'];
$temp['spent_minute'] = $timer['minute'];
$temp['spent_second'] = $timer['second'];
$temp['completed_minute'] = $top->completed_minute;
$sec_var = $top->completed_second;
if($sec_var < 0) {
$sec_var = -1 * $sec_var;
}
$temp['completed_second'] = $sec_var;
$percentile = $this->getPercentileRank($test_id,$top->percentage,$top->maximum_marks);
$temp['percentile'] = $percentile; // percentile
// $temp['rank'] = intval($percentile); // Rank
$topper_array[] = $temp;
}
//>>>>>>>>>>>>>>>>>> topper array contain Topper Percentile,now we need to get Rank according to Percentile
$topper_array = $this->rank($topper_array);
$data_array['toppers_result'] = $topper_array;
/*>>>>>>>>>>>>>>For Topper Result>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>>>>>>For Login user Percentile>>>>>>>>>>>>>>>>*/
$percentile = $this->getPercentileRank($test_id, $perc, $max_marks);
$percentile_array = $this->loginUserRank($topper_array, $percentile);
$data_array['percentile'] = $percentile_array;
/*>>>>>>>>>>>>>>For Login user Percentile End>>>>>>>>>>>>>>>>*/
/*>>>>>>>>>Get subject Wise Time of Toppers >>>>>>>>>>>>>*/
$subject_wise_time = $this->getSubjectWiseTopperTime($test_id);
$data_array['subject_wise_topper_time'] = $subject_wise_time;
/*>>>>>>>>>Get subject Wise Time of Toppers End >>>>>>>>>>>>>*/
/*>>>>>>>>>Get Answer with Time of Toppers >>>>>>>>>>>>>*/
$topper_answer_with_time = $this->topperAnswerTime($test_id);
$data_array['topper_answer_with_time'] = $topper_answer_with_time;
/*>>>>>>>>>Get Answer with Time of Toppers Ends >>>>>>>>>>>>>*/
return $this->modelMessage(1,'non','success',$data_array); exit;
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
} else {
return $this->modelMessage($this->getStatus(),$this->getError(),$this->getMessage()); exit;
}
}
I'm trying to debug this code but I don't know what am I missing here.How can this take 15 secs of time to return response back? Have I done something wrong?
When you debug than calculate the needed times with microtime(true), my guess are the DB querys for instance:
$start=microtime(true);
$answer_list = $this->loadRowList($query);
$stop=microtime(true);
$neededTime=$stop-$start;
echo "Time for answer_list $neededTime s for query $query";
Than you see what need to longest time. Than look on your query an look on your database schema. In most cases you can solve that issue by adding some indices on your db table. You can "debug" the query with explain on sql level, this will show you if you use an index.

PHP - array_push() expects parameter 1 to be array, null given in

I'm currently experiencing issues where array_push() is not working. I have ensured the arrays are directly accessible and declared correctly. Yet I'm still receiving these warnings and the values are not being pushed onto the array.
Here is my code:
include('../connstr.inc');
$email=$_REQUEST["email"];
$datafile=$_REQUEST["datafile"];
$email_safe=preg_replace("/[^a-zA-Z]/","_",$email);
$path="../uploaded_data";
$xml = simplexml_load_file("{$path}/{$email_safe}/{$datafile}.xml");
// Retreive data details for specified activity
$lapCount = $xml->Activities->Activity->Lap->count();
// Lap Variables
$totalTime = array(); $distance = array(); $maxSpeed = array();
$calories = array(); $intensity = array(); $trigMethod = array();
$avgSpeed = array();
// Convert filename to DateTime format
$datafile = convertID($datafile);
$datafile = date('Y-m-d H:i:s', strtotime($datafile));
// Variables for accurate distance calculations
$polarDistance = true;
$lapID;
$totalLapDistance;
$firstPoint = array();
$secondPoint = array();
// Collect details for each lap
for($x = 0; $x < $lapCount; $x++) {
$totalLapDistance = 0;
$lapNumber = $x+1;
$totalTime[$x] = $xml->Activities->Activity->Lap[$x]->TotalTimeSeconds;
$distance[$x] = $xml->Activities->Activity->Lap[$x]->DistanceMeters;
$maxSpeed[$x] = $xml->Activities->Activity->Lap[$x]->MaximumSpeed;
$calories[$x] = $xml->Activities->Activity->Lap[$x]->Calories;
$intensity[$x] = $xml->Activities->Activity->Lap[$x]->Intensity;
$trigMethod[$x] = $xml->Activities->Activity->Lap[$x]->TriggerMethod;
$avgSpeed[$x] = $xml->Activities->Activity->Lap[$x]->Extensions->LX->AvgSpeed;
// Store activity details into the 'detail' table
$sqlLap = "INSERT INTO lap (lapDate,lapNumber,TotalTime,distance,maxSpeed,avgSpeed,calories,intensity,trigMethod) VALUES (\"$datafile\",\"$lapNumber\",\"$totalTime[$x]\",\"$distance[$x]\",\"$maxSpeed[$x]\",\"$avgSpeed[$x]\",\"$calories[$x]\",\"$intensity[$x]\",\"$trigMethod[$x]\")";
$runLap = mysql_query($sqlLap) or die("unable to complete INSERT action:$sql:".mysql_error());
// Trackpoint variables
$altitude = array(); $tDistance = array(); $latitude = array();
$longitude = array(); $speed = array(); $pointTime = array();
// Retreive lapID
$lapID = getLapID();
// Find how many tracks exist for specified lap
$trackCount = $xml->Activities->Activity->Lap[$x]->Track->count();
$trackpointTotalCount = 1;
for($t = 0; $t < $trackCount; $t++) {
// Find out how many trackpoints exist for each track
$trackpointCount = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint->count();
// Collect details for each specificied track point
for($tp = 0; $tp < $trackpointCount; $tp++) {
$altitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->AltitudeMeters;
$tDistance[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->DistanceMeters;
$pointTime[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Time;
$latitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LatitudeDegrees;
$longitude[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Position->LongitudeDegrees;
$speed[$tp] = $xml->Activities->Activity->Lap[$x]->Track[$t]->Trackpoint[$tp]->Extensions->TPX->Speed;
// Check Track point
if(checkTP($altitude[$tp], $tDistance[$tp], $latitude[$tp], $longitude[$tp], $speed[$tp])) {
// Check if accurate distance should be calculated
if($polarDistance) {
$aa = $latitude[$tp];
$bb = $longitude[$tp];
$cc = $altitude[$tp];
if($tp == 0) {
array_push($firstPoint, $aa, $bb, $cc);
} else if($tp != 0) {
array_push($secondPoint, $aa, $bb, $cc);
}
printArray($firstPoint);
printArray($secondPoint);
// Add distance between trackpoints to total lap distance
$totalLapDistance += calcDistance($firstPoint, $secondPoint);
}
// Insert current trackpoint data into 'trackpoint' table
$sqlTC = "INSERT INTO trackpoint (tpDate,tpNumber,altitude,distance,latitude,longitude,speed,pointTime) VALUES (\"$datafile\",\"$trackpointTotalCount\",\"$altitude[$tp]\",\"$tDistance[$tp]\",\"$latitude[$tp]\",\"$longitude[$tp]\",\"$speed[$tp]\",\"$pointTime[$tp]\")";
$runTC = mysql_query($sqlTC) or die("unable to complete INSERT action:$sql:".mysql_error());
}
$trackpointTotalCount++;
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
}
}
if($polarDistance) {
if($tp != 0) {
// Update lap with more accurate distance
echo $totalLapDistance . '<br />';
$sqlUlap = "UPDATE lap SET accDistance='$totalLapDistance' WHERE lapID = '$lapID' ";
$runUlap = mysql_query($sqlUlap) or die("unable to complete UPDATE action:$sql:".mysql_error());
}
}
}
I didn't include all of the code below as there is quite a lot and I very much doubt it's relevant.
The warnings themselves only appear when trying to push a variable onto $secondPoint:
array_push($secondPoint, $aa, $bb, $cc);
However values are not being pushed onto either of the variables ($firstPoint, $secondPoint)
As a test I did echo $aa,bb and $cc and they did contain correct values.
Anybody have an idea of what I'm doing wrong?
EDIT: I have showed more of the code as I do use these arrays later, however this should not affect how the values are initially pushed? Below is some code which may affect it, namely the assign by reference?
if($polarDistance) {
if($tp != 0) {
unset($firstPoint);
$firstPoint = &$secondPoint;
unset($secondPoint);
}
}
That unset($secondPoint) will probably do it.
Try this instead:
if($polarDistance) {
if($tp != 0) {
$firstPoint = $secondPoint;
$secondPoint = array();
}
}

PHP Error Undefined Offset

Getting Notice: Undefined offset: 25 in
C:\wamp\www\finalProjectDemo\search.php on line 32
I'm trying to read in from a file and search for a specific name and address within that for output. I know a database would be best. This is for a class assignment I'm giving out that's specifically set to work this way. I believe I almost have it all, but am just getting this problem. Fairly new to PHP.
I have this code:
<html>
<body>
<?php
// read lines into array
// search array for string
// get 7 lines from there.
$i = 0;
$fileName = "addresses.txt";
$readFile = fopen($fileName, 'r');
$readByLineArray = array();
// Get search string from submission
$searchFirstName = $_POST['searchFirstName'];
$searchLastName = $_POST['searchLastName'];
$searchFirstNameSuccess = 0;
$searchLastNameSuccess = 0;
while (!feof($readFile))
{
$readByLineArray[$i] = fgets($readFile);
//echo "$readByLineArray[$i] read from array position $i";
//echo "<br />";
$i++;
}
fclose($readFile);
$arrLength = count($readByLineArray);
$currentArrayPosition = 0;
for ($x=0;$x<=$arrLength;$x++){
if ($searchFirstName == $readByLineArray[$x])
{
$searchFirstNameSuccess = 1;
$x++;
if ($searchLastName == $readByLineArray[$x])
{
$searchLastNameSuccess = 1;
$currentArrayPosition = $x - 1;
} else {
$searchFirstNameSuccess = 0;
}
}
}
for ($y=0;$y<=7;$y++){
echo "$readByLineArray[$currentArrayPosition]<br />";
$currentArrayPosition++;
}
?>
</body>
</html>
Thanks for all your help!
Ben---
Try foreach :-
foreach ($readByLineArray as $temp){
if ($searchFirstName == $temp)
{
$searchFirstNameSuccess = 1;
$x++;
if ($searchLastName == $temp)
{
$searchLastNameSuccess = 1;
} else {
$searchFirstNameSuccess = 0;
}
}
}
Change your for loop like this..
for ($x=0;$x<$arrLength;$x++){ //<--- Should be < and not <=
Say if your array count is 3 , so the array elements keys are arranged as 0,1,2. When you put <= in the looping as condition , your code will check for an non-existent key with an index of 3 which will thrown an Undefined Offset notice.
EDIT :
The easier way....
<html>
<body>
<?php
$fileName = "addresses.txt";
// Get search string from submission
$searchFirstName = $_POST['searchFirstName'];
$searchLastName = $_POST['searchLastName'];
$searchFirstNameSuccess = 0;
$searchLastNameSuccess = 0;
foreach(file($fileName) as $recno=>$records)
{
if(stripos($records,$searchFirstName)!==false && stripos($records,$searchLastName)!==false)
{
$searchFirstNameSuccess = 1;
$searchLastNameSuccess = 1;
echo "Match Found at Position : $recno";
break;
}
}
?>
</body>
</html>

Rectangle Auto Blit

I have a container rectangle and element rectangle, both are specified only in height and width. Using PHP I need to figure out what positions and orientation would allow for the most possible blits of the element within the container having absolutely no overlap.
An Example :
$container = array(5000,2000);
$element = array(300,200);
The output should be an array of "blit" arrays (or objects) like so
$blit_object = array($x,$y,$rotation_degrees);
Well, since no one is answering me, I am just going to show my "trial and error" solution in case anyone else ever needs it.
It calculates the two basic layout options and sees which one has the most and uses that.
function MakeBlits($container,$element)
{
$container_x = $container[0];
$container_y = $container[1];
$options = array();
for($i = 0;$i<=1;$i++)
{
if($i == 0)
{
$element_x = $element[0];
$element_y = $element[1];
}
else
{
$element_x = $element[1];
$element_y = $element[0];
}
$test_x = floor($container_x/$element_x);
$test_y = floor($container_y/$element_y);
$test_remainder_x = $container_x - $test_x*$element_x;
$test_remainder_y = $container_y - $test_y*$element_y;
$test_x2 = 0;
$test_x3 = 0;
$test_y2 = 0;
$test_y3 = 0;
if($test_remainder_x > $element_y)
{
$test_x2 = floor($test_remainder_x/$element_y);
$test_y2 = floor($container_y/$element_x);
}
if($test_remainder_y > $element_x)
{
$test_x3 = floor($container_x/$element_y);
$test_y3 = floor($test_remainder_y/$element_x);
}
$options[] = array(
'total'=>($test_x*$test_y)+($test_x2*$test_y2)+($test_x3*$test_y3),
'x'=>$test_x,
'y'=>$test_y,
'x2'=>$test_x2,
'y2'=>$test_y2,
'x3'=>$test_x3,
'y3'=>$test_y3
);
}
if($options[0]['total']>=$options[1]['total'])
{
$option = $options[0];
$rotate = 0;
$width = $element[0];
$height = $element[1];
}
else
{
$option = $options[1];
$rotate = -90;
$width = $element[1];
$height = $element[0];
}
$blit_objects = array();
for($i=0;$i<$option['x'];$i++)
{
for($j=0;$j<$option['y'];$j++)
{
$blit_objects[] = array(
'x'=>$i*$width,
'y'=>$j*$height,
'rotation'=>$rotate);
}
}
for($k = 0;$k < $option['x2'];$k++)
{
for($l = 0;$l < $option['y2'];$l++)
{
$blit_objects[] = array(
'x'=>$i*$width + $k*$height,
'y'=>$l*$width,
'rotation'=>$rotate+90);
}
}
for($k = 0;$k < $option['x3'];$k++)
{
for($l = 0;$l < $option['y3'];$l++)
{
$blit_objects[] = array(
'x'=>$k*$height,
'y'=>$j*$height+$l*$width,
'rotation'=>$rotate+90);
}
}
return $blit_objects;
}

Categories