Creating a chat with Laravel - php

Good night !
I managed to show information about users and content of the messages with the following code
Route::get('chat', function(){
// Get the number of days to show data for, with a default of 7
$usr1 = 121;
$usr2 = 123;
/***Obtener conversacion 121 y 123**/
$messageuser = MessageUser::with('conversaciones')->get();
foreach($messageuser as $msj){
if(($msj->id_emisor == $usr1)&&($msj->id_receptor == $usr2)){
$usuario1 = User::find($usr1);
foreach($msj->conversaciones as $conv){
echo $usuario1->name;
echo $conv->contenido;
}
}
if(($msj->id_emisor == $usr2)&&($msj->id_receptor == $usr1)){
$usuario2= User::find($usr2);
foreach($msj->conversaciones as $conv){
echo $usuario2->name;
echo $conv->contenido;
}
}
}
});
Now , I need to join this two condition into array to send the result to view , I don't know how to create this array , someone would be kind enough to help me with this ?

I would try and use the MVC architecture that Laravel is designed for in order to help you organise your code.
If your variable values are within the MessageUser model then you can easily query them without doing your if statements. If your want to keep with you style of logic then you can easily loop using a foreach within the view and then echo using double curly brackets to echo the results.

Related

PHP JSON Parsing Issue

I have this JSON output from a Government API, I need to display it using PHP. The problem is I can't use foreach more then once in a row or it doesn't work. I can't load all the criteria into the first foreach because say the first piece of data ACASS returns 3 results, all the fields after it will be displayed 3 times. Each field could return 1-10 results so there needs to be a system that accounts for variables.
I'm thinking the solution is to put all of the JSON items I need displayed into the first foreach but set them to only display if they're populated. That or use the current coding system I have but account for variable numbers somehow.
Any potential solutions are greatly appreciated.
This is the JSON output... https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY
Here's the PHP I'm using...
echo "ACASS ID:".$decoded_results['sam_data']['registration']['qualifications']['acass']['id']."</br>";
foreach($decoded_results['sam_data']['registration']['qualifications']['acass']['answers'] as $acass)
{
echo 'Answer Text:'.$acass['answerText'].'</br>';
echo 'ACASS Section:'.$acass['section'].'</br>';
}
$formerfirm = $decoded_results['sam_data']['registration']['qualifications']['acass']['answers'][2]['FormerFirm'];
echo 'Former Firm ID:'.$formerfirm['id'].'</br>';
echo 'Former Firm Year Established:'.$formerfirm['yearEstablished'].'</br>';
echo 'Former Firm Name:'.$formerfirm['name'].'</br>';
echo 'Former Firm DUNS'.$formerfirm['duns'].'</br>';
I did my best to keep this short and simple question / code wise. In summary the issue is if you look at the JSON the data hierarchy makes a lot of the information display under ACASS/Answers and then the next category. I never know how many responses there will be and I'm not sure how to account for those variables.
I would like to thank everyone on these boards who has guided me as a new member and helped me post cleaner, more concise questions. Also thank you to everyone who has taken their own personal time to help me learn to become a better programmer.
use a tool like http://jsonviewer.stack.hu/ for visualizing your json structure. It helps a lot.
<?php
$url = "https://api.data.gov/sam/v4/registrations/9606040070000?api_key=WI7nHENlp6QDMnWsb0Nnmzsv1slPDTjNM0XBoKvY";
$contents = json_decode(file_get_contents($url));
// echo var_dump($contents);
$sam_data = $contents->sam_data;
// echo var_dump($sam_data);
$registration = $sam_data->registration;
//echo var_dump($registration);
$acass = $contents->sam_data->registration->qualifications->acass;
$id = $acass->id;
echo "id: ". $id . "<br />";
//echo var_dump($acass->answers);
foreach($acass->answers as $answer) {
if(isset($answer->FormerFirm)) {
$formerFirm = $answer->FormerFirm;
echo var_dump($formerFirm);
}
}

Efficient way to make a (PHP) redirection functionality for multiple (128) database values

Currently I am working on a webpage where certain data from a database is being fetched and displayed to the user. This information is about certain project information and the lead partners of those projects. I want to implement a functionality where the user can click on a lead partner (link) and the link will redirect this user to another page (where the database information of all the organisations is on) BUT with a predefined search for only the organisations that are equal to the clicked lead partner link.
I found a solution on how to do this but the problem is that the solution (which i describe further below) isn't that good/efficient for multiple (128) organisations.. So the question is, do you know a better/more efficient solution to achieve this. To answer this question you probably also need some background information:
BACKGROUND INFORMATION
In the outputted database information (which is done in a table) there are several information columns/titles such as:
Project name
Organisations involved
Leader partner
Project website
And so on...
The fetching of the data is being done with a simple query where certain database columns have a specific identifier. For example, the project website columns is obviously a link, so in the query it is being done as follows: $SomeQueryVar = ("SELECT project_website as LINK FROM xxxx WHERE project_website ('$some_website') "); -- Just a short example to clarify things.
For the displaying, the data is being 'catched' like so:
if(count($SomeQueryVar)>0){
for($i=0;$i<count($SomeQueryVar);$i++){
echo "<tr>";
foreach($SomeQueryVar[$i] as $key=>$value){
echo "<td>";
$b=unserialize($value);
if($key =='LINK' && $value != NULL){
$first = true;
array_filter($b);
foreach($b as $y){
echo ''."Project website".'';
$first = false;
if(!$first) break;
}
} else {
echo $value;
}
echo "</td>";
}
echo "</tr>";
}
}
As you can see in the above code, certain database columns need other displaying as the rest. For example, links must be clickable instead of just being plain text. These 'exceptions' are being catched with the if $key ==, for the data that just needs regular displaying (plain text) there is the last else inserted that just echo's the $value.
MY FOUND SOLUTION
So regarding the question, i found out that i can create redirection links using the ?SomePage on the projects page and using this 'added link value' on the organisations page to compare it. If the link is equal, then do the specific query. But it is probably easier to paste the code here:
The 'CATCHING' part
To catch a specific lead partner is also used an identifier in my query called ORG (which stands for organisation). So here is the code where i catch the organisations table:
if($key =='ORG' && $value != NULL){
$needle = array('Brainport','Development','BRAINPORT',
'brainport','DEVELOPMENT','development');
$needle2 = array('Casa','CASA', 'casa');
if (strpos_arr($value,$needle) !== false) {
echo '<a href="http://portal.e-ucare.eu/database/organisations/?a=brainport" >'.$value.'</a>';
}
if (strpos_arr($value,$needle2) !== false) {
echo '<a href="http://portal.e-ucare.eu/database/organisations/?a=casa" >'.$value.'</a>';
}
}
In the above code i just created it for 2 organisations (brainport and casa). For this solution i used a function called strpos_arr which searches for the needle in the haystack;) So in the code above i set the needles to the names in the database where it has to create a link for. So if for example a company with the word Brainport exists in the database, this 'catcher' will see this and display the organisation and make the name clickable.
The strpos_arr function for the $needle is as follows:
function strpos_arr($value, $needle) {
if(!is_array($needle)) $needle = array($needle);
foreach($needle as $what) {
if(($pos = strpos($value, $what))!==false) return $pos;
}
return false;
}
In the redirection page the code will also catch certain links to make queries for that link -- so for the brainport link this is http://portal.e-ucare.eu/database/organisations/?a=brainport -- in the second page code this link is catched like so:
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if($host == 'portal.e-ucare.eu/database/organisations/?a=brainport')
{
$link_word = "Brainport";
$tmp = $wpdb->get_results("
SELECT
name_of_company__organization, company_location,
company_website as LINK, organisation_type,
organisation_active_in_, organisation_scope,
organisation_files as DOC
FROM
wp_participants_database
WHERE
name_of_company__organization REGEXP ('$link_word')
ORDER BY
name_of_company__organization ASC
");
}
With this solution i can do what i want, BUT like i said in the beginning, i need this for not just 2 organisations but 128!! This would mean i have to copy the catching code blocks on both pages 128 times!! This is obviously not very efficient..
So is there any more efficient way to achieve this? Sorry if it is a bit unclear but i found it quite hard to easily wright this down;)
Anyway, thank you in advance!
The firts part you can rewrite to
if($key =='ORG' && $value != NULL){
$needles = array(
'brainport'=>array('Brainport','Development','BRAINPORT','brainport','DEVELOPMENT','development'),
'casa'=>array('Casa','CASA', 'casa')
);
foreach($needles AS $nkey => $needle){
if(strpos_arr($value,$needle) !== false) {
echo "<a href='http://portal.e-ucare.eu/database/organisations/?a={$nkey}' >{$value}</a>";
}
}
}
For the second part make an array like
[EDIT]
$link_words = array(
'portal.e-ucare.eu/database/organisations/?a=brainport'=>'Brainport',
'portal.e-ucare.eu/database/organisations/?a=casa'=>'Casa',
);
then you can use
$host = $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
if(!empty($link_words[$host])){
$link_word = $link_words[$host];
$tmp = $wpdb->get_results("
SELECT
name_of_company__organization, company_location, company_website as LINK, organisation_type, organisation_active_in_, organisation_scope, organisation_files as DOC
FROM
wp_participants_database
WHERE
name_of_company__organization REGEXP ('$link_word')
ORDER BY
name_of_company__organization ASC
");
}

Splitting an external array to give different titles

I've been trying to figure out how to split the array and add different titles for each of the separate titles on the page, for each of the different things that this displays. However the most I can manage to do is add a comma between the numbers and words.
I would like to add selling"1st variable price"second variable" etc however I don't quite know how to do anything other than to turn this very confusing looking bunch of letters:
user name and notes 01001000013972583957ecCCany amount-w378- v west
into anything other than this:
0,100,10000,1397258395,7ec,CC,any amount-w378- v west
Also, this is what it looks like in its JSON form:
{"selling":"0","quantity":"100","price":"10000","date":"1397258395","rs_name":"7ec","contact":"CC","notes":"any amount-w378- v west"}
I just want all the information that is in there to displayed like that however I'm not quite sure how to add the titles that is in the JSON data. I also don't have access to the external site to change anything.
A little background: what I am trying to achieve is a price look-up for a game on my website from an external site. I tried to use an iframe but it was terrible; I would rather just manually display it rather than showing their site from mine - their style and my style clash terribly.
$json = file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe');
$obj = json_decode($json,true);
$blah1 = implode( $obj[0]["offers"][1]);
print_r($blah1);
If you know where it is, you should be able to just grab it and show it out?
You can use a failsafe to check if it is present with is_array() and isset() functions - see php.net docs on them.
Your print_r should give you good valid info -- try to wrap it around <pre></pre> tags before for better readability or view the source - it will be easier!
<pre><?php print_r($obj) ?></pre>
This should be your starting point, and from here you will either take the first one of your items or loop through all with
foreach ($obj as $o) { //should be $objects, not $obj
//do whatever with $o, like echo $o['price']
}
Each offers row is a table with each field separated by row:
$item = json_decode(file_get_contents('http://forums.zybez.net/runescape-2007-prices/api/rune+axe'));
while ($offer = array_shift($item[0]->offers)) {
echo "<table>" . PHP_EOL;
foreach ($offer as $field => $value) {
echo "<tr><th>$field</th><td>$value</td></tr>" . PHP_EOL;
}
echo "</table>" . PHP_EOL;
}
http://codepad.org/C3PQJHqL
Tables in HTML:
http://jsfiddle.net/G5QqZ/

I need help sorting out an if statement in a simplexml statement

Some basic background ...
I have a form that enters data to an xml file and another page that displays the data from teh xml depending that it meets the requirements . All of this I have managed to get done and thanks to a member on here I got it to show only the data as long as it has todays date and status is out . But I am left with the problem of trying to sort an if statement which needs to show data if it has it or show another div if not .
My Code ...
$lib = simplexml_load_file("sample.xml");
$today = date("m/d/y");
$query = $lib->xpath("//entry[.//date[contains(., '$today')]] | //entry[.//status[contains(., 'out')]]");
foreach($query as $node){
echo "<div id='one'>$node->name</div>
<div id='two'>$node->notes</div>
<div id='three'><div class='front'>$node->comments</div></div>";
}
So to reiterate if query returns matched data do the foreach else show another div
I only wish to know the right code for the if else statement if soneone could help with this I would be very grateful and will up vote any answer as soon as I have the reputation in place . I also apologise in advance if the question has been asked before or if it is too vague thanks again .
If xpath fails to resolve the path, it will return false (see here). Wrap the foreach loop in a simple check:
if( $query ) {
foreach($query as $node){
...
}
}
else {
// Echo the special div.
}
Since PHP is loose typed, if xpath happens to return an empty array, this check will also handle that case. Be aware that if the xpath call does return false, there may be a separate error at play that may require additional or alternative handling.

How To Stop Duplicates Being Listed On PHP Results?

I've made up a PHP script which assigns a score to listings on a website and assigns it to the results page. I have got it to work in that it shows the score and the details but it keeps listing the same results over and over.
I can't work out what it is doing but there is a small section of code I was hoping would prevent duplicate listings. Could anyone give it a tweak and see if I am going wring somewhere?
The Code is:
$dupCatch .= $adId.",";
$dupResults = explode(',', $dupCatch);
foreach($dupResults as $dupResult){
if($dupResult == $adId){
print "";
} else {
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
}
Thanks in advance!
Jack
The problem is that you add your current $adId to the duplicate list before you check if it is there - which it will always be, of course.
Storing a bunch of numbers in a string, explodeing it every time, is a little weird, use an array instead. You also don't need to manually loop through all the items, just use in_array()
if( !in_array($adId, $dupCatch) ){
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
$dupCatch[] = $adId;
Needless to say: it would be a better idea to fix the part that gives you the duplicate results in the first place.
You can either try to use array_unique from php side or use unique attribute at field in mysql this way duplicates can be prevent before even inserting them.

Categories