I have a bunch of data in array without sorting, i need to categorize the data into set and display to the public. This is how the data loop without categorisation.
foreach ($info as $i){
if ($i->metadataKey==1018){
echo $i->businessId . " - " . $i->businessName . " - " . $i->metadataValue;
}
if ($i->metadataKey==1021){
echo ", " . $i->metadataValue;
echo "<br/>";
}
}
it's a joined table and one business having numbers of metadata (associated by metadataKey and metadataValue). The following is the code i getting data from database.
$info = DB::table('business')
->leftJoin('business_meta', 'business.Id', '=', 'business_meta.businessId')
->get();
Or you may reference the following table
Business
id
business name
Business_meta
metadatakey
metadatavalue
businessId
one business will have couple of business meta, 1018 is state and 1021 is country
I need to assorciate it into sort array or some pattern of data to display it according to "state, country" on the public site.
Which mean, it may be something like
California, US
Business 1
Business 2
Texas, US
Business 3
Please advice how can i make it. Thanks.
I think usort is all you need. Just create your custom function for sorting both levels of your array.
Related
I'm currently working on a project with my friends,
so let me explain:
We have a mySql database filled with english postcode from London, one table with universities, and one with hosts, what we want is to actually calculate the public transport travel time between all the host and the universities and save it into another table of the database that will have the host postcode, the university post code and the travel time between the both on one line, and etc...
For that we are doing http request to the tfl API that return to us a JSON with all the travel details (and of course the travel time), that we then decode and keep only what we want (travel time).
The problem is that we have a quite big database with almost 250 host and 800 universities that give us around 200 000 request and a too long process time to be used (with the api response time and the php treatment, around 19h)
We tried to see if we could use the cURL method to split the process between multiple loop so that we can divide the process time by the number of cURL we made but we can't manage to figure how we can do that...
The final goal is to make a small local app that when we select one university it give us the nearests 10 hosts in public transport.
Does anyone have any experience with that kind of things and can help us ?
Here is what we have right now :
//postCodeUni list contains all the universites objects
foreach ($postCodeUni as $uniPostCode) {
//here we take the postcode from the university object
$uni = $uniPostCode['Postcode'];
//postCodeHost list contains all the host objects
foreach ($postCodeHost as $hostPostCode) {
//here we take the postcode from the host object
$host = $hostPostCode['Postcode'];
//here we make an http request to the tfl api that return us a journey between the two post codes (a json with all the journey details)
$data = json_decode(file_get_contents('https://api.tfl.gov.uk/journey/journeyresults/' . $uni . '/to/' . $host . '?app_key=a59c7dbb0d51419d8d3f9dfbf09bd5cc'), true);
//here we save the multiple duration times (because there is different ways to travel between two point with public transport)
$duration = $data['journeys'];
$tableTemp = [];
foreach ($duration as $durations) {
$durationns = $durations['duration'];
array_push($tableTemp, $durationns);
}
//We then take the shorter one
$min = min($tableTemp);
echo "Shorter travel time : " . $min . " of travel between " . $uni . " and ". $host . " . <br>";
echo "<br>";
//We then save this time in a table that will contain the travel time of all the journeys to do comparaison
array_push($tableAllRequest, array($uni . " and ". $host => $min));
}
}
There are many ways to achieve this however the easiest imo would be to use Guzzle Async (cURL multi interface under the hood). Take a look at this answer - Guzzle async requests not really async? example below,
<?php
use GuzzleHttp\Promise;
use GuzzleHttp\Client;
$client = new Client(['base_uri' => 'http://httpbin.org/']);
// Initiate each request but do not block
$promises = [
'image' => $client->getAsync('/image'),
'png' => $client->getAsync('/image/png'),
'jpeg' => $client->getAsync('/image/jpeg'),
'webp' => $client->getAsync('/image/webp')
];
// Wait on all of the requests to complete. Throws a ConnectException
// if any of the requests fail
$results = Promise\unwrap($promises);
// Wait for the requests to complete, even if some of them fail
$results = Promise\settle($promises)->wait();
// Loop through each response in the results and fetch data etc
foreach($results as $promiseKey => $result) {
// Data response
$dataOfResponse = ($result['value']->getBody()->getContents());
// Status
echo $promiseKey . ':' . $result['value']->getStatusCode() . "\r\n";
}
I want to build a Recommendation system that recommends people base on their preferences towards user details for example if User1 wants someone who is male and lives america, an array would be made of this being User1{male, america} while the second array would be the other users details for example user2 being female and from america her array would be User2{female, america}, user 3 being {male, america} I want to be able to find the similarity distance between user 1 and the other users array and base on the score it would be listed from the highest to the lowest.
The dirty way of doing it:
foreach($item in $array_one){
foreach($item_two in $array_two){
if($item == $item_two){
echo "Euston, we found a match!";
}
}
}
The clean way of doing it:
$intersection = array_intersect($array_one, $arrary_two);
if (in_array($value_to_look_for, $intersection)) {
echo "Euston, we have a match!";
}
I'm using the PHPcoord package to try and convert a UK 6 figure Grid reference to Lat & Long.
According to the examples given in the link above. This is a two part process.
Part 1) Converting the 6 Figure Grid Reference into an OSGB grid reference.
ie: Convert TG514131 into (651400, 313100).
The example given is:
$os6 = "TG514131";
echo "Six figure string: " . $os6 . "<br />";
$os6x = getOSRefFromSixFigureReference($os6);
echo "Converted to OS Grid Ref: " . $os6x->toString() . " - " . $os6x->toSixFigureString();
Six figure string: TG514131
Converted to OS Grid Ref: (651400, 313100) - TG514131
Part 2) converts the OSGB reference into Lat & Long by:
$os1 = new OSRef(651409.903, 313177.270);
echo "OS Grid Reference: " . $os1->toString() . " - " . $os1->toSixFigureString() . "<br />";
$ll1 = $os1->toLatLng();
echo "Converted to Lat/Long: " . $ll1->toString();
the problem I am having is that I can't get the output of stage 1:
$os6x->toString()
into the input of stage 2:
$os1 = new OSRef(651409.903, 313177.270);
I've tried converting $os6x->toString() into a variable and then using:
$myvariable = $os6x->toString();
$os1 = new OSRef($myvariable);
or
$os1 = new OSRef$myvariable;
or
$os1 = new OSRef . $myvariable;
and unsurprisingly, none work.
As you can tell I'm not very good at this and am struggling to find any help on Google.
My next step would be to pattern match $myvariable and then split it into two variables and plug them in like this:
$os1 = new OSRef($number1, $number2);
But I'm sure this is not the correct way to achieve this and I'm missing something very simple.
Thanks for your help.
EDIT
I posted the same question on Experts-Exchange and got an answer. Here it is for anyone who has a similar question:
"Your call to the getOSRefFromSixFigureReference() returns an instance of the OSRef class. This class has 2 properties - easting and northing, so to get at those 2 values you would access the properties:
$os6x->easting;
$os6x->northing;
In your question, you look like you're trying to access those 2 properties so you can create a new OSRef object. That's not needed because $os6x is already an instance of the OSRef class, so you can already call the various methods on it:
echo $os6x->toLatLng();
I posted the same question on Experts-Exchange and got an answer there. Here it is for anyone who has a similar question:
"Your call to the getOSRefFromSixFigureReference() returns an instance of the OSRef class. This class has 2 properties - easting and northing, so to get at those 2 values you would access the properties:
$os6x->easting;
$os6x->northing;
In your question, you look like you're trying to access those 2 properties so you can create a new OSRef object. That's not needed because $os6x is already an instance of the OSRef class, so you can already call the various methods on it:
echo $os6x->toLatLng();
I have integrated Yelp reviews into my directory site with each venue that has a Yelp ID returning the number of reviews and overall score.
Following a successful MySQL query for all venue details, I output the results of the database formatted for the user. The Yelp element is:
while ($searchresults = mysql_fetch_array($sql_result)) {
if ($yelpID = $searchresults['yelpID']) {
require('yelp.php');
if ( $numreviews > 0 ) {
$yelp = '<img src="'.$ratingimg.'" border="0" /> Read '.$numreviews.' reviews on <img src="graphics/yelp_logo_50x25.png" border="0" /><br />';
} else {
$yelp = '';
}
} //END if ($yelpID = $searchresults['yelpID']) {
} //END while ($searchresults = mysql_fetch_array($sql_result)) {
The yelp.php file returns:
$yrating = $result->rating;
$numreviews = $result->review_count;
$ratingimg = $result->rating_img_url;
$url = $result->url;
If a venue has a Yelp ID and one or more reviews then the output displays correctly, but if the venue has no Yelp ID or zero reviews then it displays the Yelp review number of the previous venue.
I've checked the $numreviews variable type and it's an integer.
So far I've tried multiple variations of the "if ( $numreviews > 0 )" statement such as testing it against >=1, !$numreviews etc., also converting the integer to a string and comparing it against other strings.
There are no errors and printing all of the variables returned gives the correct number of reviews for each property with venues having no ID or no reviews returning nothing (as opposed to zero). I've also compared it directly against $result->review_count with the same problem.
Is there a better way to make the comparison or better format of variable to work with to get the correct result?
EDIT:
The statement if ($yelpID = $searchresults['yelpID']) { is not operating as it should. It is identical to other statements in the file, validating row contents which work correctly for their given variable, e.g. $fbID = $searchresults['fbID'] etc.
When I changed require('yelp.php'); to require_once('yelp.php'); all of the venue outputs changed to showing only the first iterated result. Looking through the venues outputted, the error occurs on the first venue after a successful result which makes me think there is a pervasive piece of code in the yelp.php file, causing if ($yelpID = $searchresults['yelpID']) { to be ignored until a positive result is found (a yelpID in the db), i.e. each venue is correctly displayed with a yelp number of reviews until a blank venue is encountered. The preceding venues' number of reviews is then displayed and this continues for each blank venue until a venue is found with a yelpID when it shows the correct number again. The error reoccurs on the next venue output with no yelpID and so on.
Sample erroneous output: (line 1 is var_dump)
string(23) "bayview-hotel-bushmills"
Bayview Hotel
Read 3 reviews on yelp
Benedicts
Read 3 reviews on yelp (note no var_dump output, this link contains the url for the Bayview Hotel entry above)
string(31) "bushmills-inn-hotel-bushmills-2"
Bushmills Inn Hotel
Read 7 reviews on yelp
I suspect this would be a new question rather than clutter/confuse this one further?
END OF EDIT
Note: I'm aware of the need to upgrade to mysqli but I have thousands of lines of legacy code to update. For now I'm working on functionality before reviewing the code for best practice.
Since the yelp.php is sort of a blackbox; the best explanation for this behavior would be that it only set's those variables if it finds a match. Updating your code to this should fix that:
unset($yrating, $numreviews, $ratingimg, $url);
require('yelp.php');
I also noticed this peculiar if-statement, do you realize that's an assignment or is this a copy/paste error? If you want to test (that's what if is for)
if ($yelpID == $searchresults['yelpID']) {
For a personal project, I need to build a forum using PHP and MySQL. It is not possible for me to use an already-built forum package (such as phpBB).
I'm currently working through the logic needed to build such an application, but it's been a long day and I'm struggling with the concept of handling unread posts for users. One solution I had was to have a separate table which essentially holds all post IDs and user IDs, to determine if they've been read:
tbl_userReadPosts: user_id, post_id, read_timestamp
Obviously, if a user's ID appears in this table, we know they've read the post. This is great, except if we have thousdands of posts per day (which is more than possible in the system which is being proposed), and thousdands of users. This table would become huge within a matter of days, if not hours.
Another option would be to track the user's last activity as a timestamp, and then retrieve all posts made after their last activity was updated. This works in theory, but let's say a user is writing an extremely long post, and in the meantime several members also start new threads or reply to posts in other threads. When the user submits his new post, his last activity would be updated, and thus not match those made in the meantime.
Does anyone have experience with this, and how did you tackle it?
I've checked in phpBB and it seems that the system assigns a custom session to each user, and works on that basis, but the documentation is pretty sparse as to how this deals with unread posts.
Thoughts and opinions gratefully received, as always.
Sorry for the quick answer but I only have a second. You definitely do not want to store the read information in the database, as you've already deduced, this table would become gigantic.
Something in between what you've already suggested: Store the users last activity, and in conjunction with storing information of what they've seen in the cookie, to determine which threads/posts they've read already.
This offloads the storage to the client side cookie, which is far more efficient.
A table holding all user_ids and post_ids is a bad idea, as it grows exponentially. Imagine if your forum solution grew to a million posts and 50,000 users. Now you have 50 billion records. That'll be a problem.
The trick is to use a table as you said, but it only holds posts which have been read since the this login, of posts which were posted between the last login and this login.
All posts made prior to the last login are considered read.
IE, I last logged in on 4/3/2011, and then I log in today. All posts made before 4/3/2011 are considered read (they're not new to me). All posts between 4/3/2011 and now, are unread unless they are seen in the read table. The read table is flushed each time I log in.
This way your read posts table should never have more than a couple hundred records for each member.
Instead of having a new row for every post*user, you can have a field in the user-table that holds a comma-separated string with post-IDs that the user has read.
Obviously the user doesn't need to know that there are unread posts from 2 years ago, so you only display "New post" for posts made in the last 24 hours and is not in the comma-separated string.
You could also solve this with a session variable or a cookie.
This method stores the most recently-accessed postID separately for each forumID.
It's not as fine-grained as a solution that keeps track of each post individually, but it shrinks the amount of data that you need to store per user and still provides a decent way to keep track of a user's view history.
<?php
session_start();
//error_reporting(E_ALL);
// debug: clear session
if (isset($_GET['reset'])) { unset($_SESSION['activity']); }
// sample data: db table with your forum ids
$forums = array(
// forumID forumTitle
'1' => 'Public Chat',
'2' => 'Member Area',
'3' => 'Moderator Mayhem'
);
// sample data: db table with your forum posts
$posts = array(
// postID forumID postTitle
'12345' => array( 'fID'=>'1', 'title'=>'Hello World'),
'12346' => array( 'fID'=>'3', 'title'=>'I hate you all'),
'12347' => array( 'fID'=>'1', 'title'=>'Greetings!'),
'12348' => array( 'fID'=>'2', 'title'=>'Car thread'),
'12349' => array( 'fID'=>'1', 'title'=>'I like turtles!'),
'12350' => array( 'fID'=>'2', 'title'=>'Food thread'),
'12351' => array( 'fID'=>'3', 'title'=>'FR33 V1AGR4'),
'12352' => array( 'fID'=>'3', 'title'=>'CAPSLOCK IS AWESOME!!!!!!!!'),
'12353' => array( 'fID'=>'2', 'title'=>'Funny pictures thread'),
);
// sample data: db table with the last read post from each forum
$userhist = array(
// forumID postID
'1' => '12344',
'2' => '12350',
'3' => '12346'
);
// reference for shorter code
$s = &$_SESSION['activity'];
// store user's history into session
if (!isset($s)) { $s = $userhist; }
// mark forum as read
if (isset($_GET['mark'])) {
$mid = (int)$_GET['mark'];
if (array_key_exists($mid, $forums)) {
// sets the last read post to the last entry in $posts
$s[$mid] = array_search(end($posts), $posts);
}
// mark all forums as read
elseif ($mid == 0) {
foreach ($forums as $fid=>$finfo) {
// sets the last read post to the last entry in $posts
$s[$fid] = array_search(end($posts), $posts);
}
}
}
// mark post as read
if (isset($_GET['post'])) {
$pid = (int)$_GET['post'];
if (array_key_exists($pid, $posts)) {
// update activity if $pid is newer
$hist = &$s[$posts[$pid]['fID']];
if ($pid > $hist) {
$hist = $pid;
}
}
}
// link to mark all as read
echo '<p>[Read All]</p>' . PHP_EOL;
// display forum/post info
foreach ($forums as $fid=>$finfo) {
echo '<p>Forum: ' . $finfo;
echo ' [Mark as Read]<br>' . PHP_EOL;
foreach ($posts as $pid=>$pinfo) {
if ($pinfo['fID'] == $fid) {
echo '- Post: ' . $pid . '';
echo ' - ' . ($s[$fid] < $pid ? 'NEW' : 'old');
echo ' - "' . $pinfo['title'] . '"<br>' . PHP_EOL;
}
}
echo '</p>' . PHP_EOL;
}
// debug: display session value and reset link
echo '<hr><pre>$_SESSION = '; print_r($_SESSION); echo '</pre>' . PHP_EOL;
echo '<hr>[Reset Session]' . PHP_EOL;
?>
Note: Obviously this example is for demonstration purposes only. Some of the structure and logic may need to be changed when dealing with an actual database.
Phpbb2 has implemented this fairly simple. It just shows you all post since your last login. This way you don’t need to store any information about what the user actually has seen or read.