Count and print values of HTTP API - php

Looking for help in counting all values that are present in HTTP API. The link below outputs the values of multiple data points by date. What I am trying to achieve is a count on each value so that instead of
a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;}
I want to output the above nb_pageviews as a key with the value of the dates combined - 2056.
Example Link for API is https://demo.piwik.org/?module=API&method=Actions.get&idSite=7&period=day&date=last2&format=php&token_auth=anonymous
And the PHP to display this is
$url = "https://demo.piwik.org/";
$url .= "?module=API&method=Actions.get";
$url .= "&idSite=7&period=day&date=last2";
$url .= "&format=php";
$url .= "&token_auth=anonymous";
$fetched = file_get_contents($url);
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
foreach ($content as $row) {
$pageviews = $row['nb_pageviews'];
print("<div>$pageviews</div>\n");
}
Please note that the above link contains multiple other values that I will be wanting to do the same with, yet for ensuring the readability of this question I have kept the values simple and to just the one.

Just use the combined assignment operator, and be sure to set defaults of 0, before the loop.
$fetched = 'a:2:{s:10:"2018-01-03";a:9:{s:12:"nb_pageviews";d:2031;s:17:"nb_uniq_pageviews";d:964;s:12:"nb_downloads";d:2;s:17:"nb_uniq_downloads";d:2;s:11:"nb_outlinks";d:68;s:16:"nb_uniq_outlinks";d:64;s:11:"nb_searches";d:33;s:11:"nb_keywords";d:16;s:19:"avg_time_generation";d:0.78600000000000003;}s:10:"2018-01-04";a:9:{s:12:"nb_pageviews";d:25;s:17:"nb_uniq_pageviews";d:10;s:12:"nb_downloads";i:0;s:17:"nb_uniq_downloads";i:0;s:11:"nb_outlinks";d:1;s:16:"nb_uniq_outlinks";d:1;s:11:"nb_searches";d:2;s:11:"nb_keywords";d:2;s:19:"avg_time_generation";d:0.79300000000000004;}}';
$content = unserialize($fetched);
// case error
if (!$content) {
print("NO DATA");
}
$pageviews = 0;
$uniq_pageviews = 0;
// and on, with your other vars you're looking to sum...
foreach ($content as $row) {
$pageviews += $row['nb_pageviews'];
$uniq_pageviews += $row['nb_uniq_pageviews'];
}
var_export(['pageviews' => $pageviews, 'uniq_pageviews' => $uniq_pageviews]);
Working demo: https://eval.in/930183
// Output
array (
'pageviews' => 2056.0,
'uniq_pageviews' => 974.0,
)
To print these values, you might replace the var_export line with something like this:
$data = [
'pageviews' => $pageviews,
'uniq_pageviews' => $uniq_pageviews
];
Which you could output in some HTML like so:
<div class="col-md-4"><?php echo $data['pageviews']; ?></div>
<div class="col-md-4"><?php echo $data['uniq_pageviews']; ?></div>

Related

json_decode showing no data

I'm using below logic to store data in JSON format in MySQL using PHP.
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
session_start();
$date = new Date();
$modified = $date->getDate();
$query = ' UPDATE pages SET last_updated_user_author_id = "'.$_SESSION['user_id'].'", data = "'.htmlentities($store, ENT_QUOTES).'", modified = "'.$modified.'" WHERE id = "'.$pageID.'" ';
Then while decoding the data i'm using below logic:
$query = ' SELECT data FROM pages WHERE id = "'.$_POST['pageID'].'" ';
$connection = $this->establish_connection();
$data = $connection->query($query);
$connection->close();
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$var = html_entity_decode($row['data']);
echo json_decode($var);
}
}
While json_decode it shows no data in response, when i did var_dump it shows null, but if i did not do json_decode and only used html_entity_decode() i get below output
{"page_base_url":"http://www.myblog.com/about/contact/"}{"page_url_revision":"http://www.myblog.com/about/contact/"}{"page_url_alternate":"http://www.myblog.com/about/contact/"}{"page_url_shortlink":"http://www.myblog.com/about/contact/"}{"page_url_canonical":"http://www.myblog.com/about/contact/"}{"page_title":"Example | Contact"}{"page_name":"Example Contact"}{"page_type":"WebSite"}{"page_meta_description":"Want to get in touch with us? You're on the correct page, you can get in touch with us by filling the form below. We will get in touch with you with 24 hours."}{"page_keywords":["example","contact","support","help","getintouch","feedback","bug","updates"]}
I'm not sure where i'm going wrong, could anybody help me out here?
I want to give an eccho in json_encode format as a response to ajax call. i use below logic to do so
echo json_encode(
array(
"type" => "error",
"status" => "Error While Retrieving Data!",
"message" => $error
)
);
I think you need something like:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[] = array($value[1] => $value[2]);
else
$store[] = array($value[1] => trim($value[2]));
}
$save = json_encode($store);
or even (if your $value[1] is always unique within the loop)
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
$save = json_encode($store);
then use $save to store in your table. I'm not 100% on that, though.
The string you've shown is not valid JSON. If you wanted to store a list of objects like that in JSON format, they need to be within an array, and separated by commas. Otherwise they are just unrelated individual objects and cannot be decoded as a single block of JSON.
Therefore you need to build an array in PHP and then encode the whole thing at the end. Something like this:
$storedata = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$storedata[] = array($value[1] => $value[2]);
else
$storedata[] = array($value[1] => trim($value[2]));
}
$jsondata = json_encode($storedata);
And then use $jsondata in your SQL statement.
Your problem is your "saving" to the database. You encode every key-value-pair in an own json-string and concat those json-strings.
Your snippet
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store .= json_encode(array($value[1] => $value[2]));
else
$store .= json_encode(array($value[1] => trim($value[2])));
}
Yields $store = "{key1:value1}{key2:value3}{key3:value3}". Note all the brackets, you have 3 distinct json-objects with a single key-value pair in your string, instead of one json-object with 3 key-value-pairs.
However, I assume you want a single json-object with the key-value-pairs as result like the folling?
$store = "{
key1:value1,
key2:value2,
key3:value3
}";
If so, you need to build your array differently:
$store = array();
foreach ($_POST['data'] as $key => $value)
{
if($value[1] == "page_keywords")
$store[$value[1]] = $value[2];
else
$store[$value[1]] = trim($value[2]);
}
And please, for the safety of everyone, your code is vulnerable of sql-injections. Please fix that, too.

What is the best way to search through an array to return the key of a sub value

I'm trying to filter an array (derived from a json object), so as to return the array key based on the value. I'm not sure if array search $key = array_search($value, $array); is the best way to do this (I can't make it work), and I think there must be a better way.
So far I've got this, but it isn't working. Grateful for any help!
public function getBedroomData(array $data,$num_beds = null,$type) {
$data = (array) $data;
if($num_beds > 0) {
$searchstring = "avg_".$num_beds."bed_property_".$type."_monthly";
} else {
$searchstring = "avg_property_".$type."_monthly";
}
$avg_string = array_search($data, $searchstring);
return $avg_string;
}
The array consists of average property prices taken from the nestoria api as follows:
http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json
This returns a long json object. My problem is that the data isn't consistent - and I'm looking for the quickest (run time) way to do the following:
$data['response']['metadata']['0'] //= data to return, [0] unknown
$data['response']['metadata']['0']['metadata_name'] = "avg_1bed_property_rent_monthly" //= string I know!
$data['response']['metadata']['1'] //= data to return, [1] unknown
$data['response']['metadata']['1']['metadata_name'] = "avg_1bed_property_buy_monthly" //= string I know!
$data['response']['metadata']['2'] = //= data to return, [2] unknown
$data['response']['metadata']['2']['metadata_name'] = "avg_2bed_property_buy_monthly" //= string I know!
.....
.....
.....
$data['response']['metadata']['10'] = avg_property_rent_monthly
$data['response']['metadata']['11'] = avg_property_buy_monthly
$data['response']['metadata'][most_recent_month] = the month reference for getting the data from each metadata list..
It isn't possible to filter the initial search query by number of bedrooms as far as I can work out. So, I've just been array slicing the output to get the information I've needed if bedrooms are selected, but as the data isn't consistent this often fails.
To search inside that particular json response from nestoria, a simple foreach loop can be used. First off, of course call the json data that you need. Then, extract the whole data, the the next step if pretty straightforward. Consider this example:
$url = 'http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
$metadata = $data['response']['metadata'];
// dummy values
$num_beds = 1; // null or 0 or greater than 0
$type = 'buy'; // buy or rent
function getBedroomData($metadata, $num_beds = null, $type) {
$data = array();
$searchstring = (!$num_beds) ? "avg_property_".$type."_monthly" : "avg_".$num_beds."bed_property_".$type."_monthly";
$data['metadata_name'] = $searchstring;
$data['data'] = null;
foreach($metadata as $key => $value) {
if($value['metadata_name'] == $searchstring) {
$raw_data = $value['data']; // main data
// average price and data points
$avg_price = 0;
$data_points = 0;
foreach($raw_data as $index => $element) {
$avg_price += $element['avg_price'];
$data_points += $element['datapoints'];
}
$data_count = count($raw_data);
$price_average = $avg_price / $data_count;
$data_points_average = $data_points / $data_count;
$data['data'][] = array(
'average_price' => $price_average,
'average_datapoints' => $data_points_average,
'data' => $raw_data,
);
}
}
return $data;
}
$final = getBedroomData($metadata, $num_beds, $type);
print_r($final);

Facebook user table fql to json_encode

I am using user table from fql.I am passing array to json_encode(). Facebook json format is not corrct, it is excluding []. How do I add this in my code.
Below code is a example but I do not under stand that code.
user table https://developers.facebook.com/docs/reference/fql/user
I want name,uid.
//to get album cover
$fql2 = "select src from photo where pid = '" . $values['cover_pid'] . "'";
$param2 = array(
'method' => 'fql.query',
'query' => $fql2,
'callback' => ''
);
$fqlResult2 = $facebook->api($param2);
$jsarr = array();
foreach( $fqlResult2 as $keys2 => $values2){
}
if ($values['name'] != 'Profile Pictures'){
$jsarr['src'] = $album['src'];
$count += 1;
if ($count == 1){
$outputStr .= "[";}
else {
$outputStr .= ",";}
$outputStr .= json_encode($values2);
}
}
$outputStr .= "]";
$outputStr = str_replace("{","[",$outputStr);
$outputStr = str_replace("}","]",$outputStr);
echo $outputStr;
}
?>
When you use the Facebook PHP SDK, it automatically decodes the returned json object into a PHP array. If you need a json object from it, you'll have to use json_encode on it after you finish processing it.
You've got some major problems with your php code. Just to get started:
Your foreach loop ends as soon as it starts with the } on the next line.
Where do you define the variables $values and $album?
You are referencing $values2 outside of your foreach loop.
You are appending to an uninitialized variable on your line $outputStr .= "[";.
If you pass json_encode() a proper php array of data, it will make a complete json object. You shouldn't need to be appending brackets of any kind.

PHP Reconstruct array Paypal TransactionSearch Function

I am making a call to Paypals API TransactionSearch and I am getting back a flat array of data. I am needing to reconstruct this array. Here is the structure that I get back from paypal:
array(36){
[
"L_TIMESTAMP0"
]=>string(28)"2012%2d09%2d18T22%3a10%3a13Z"[
"L_TIMESTAMP1"
]=>string(28)"2012%2d09%2d18T19%3a55%3a41Z"[
"L_TIMESTAMP2"
]=>string(28)"2012%2d09%2d18T19%3a55%3a41Z"[
"L_TIMEZONE0"
]=>string(3)"GMT"[
"L_TIMEZONE1"
]=>string(3)"GMT"[
"L_TIMEZONE2"
]=>string(3)"GMT"[
"L_TYPE0"
]=>string(7)"Payment"[
"L_TYPE1"
]=>string(7)"Payment"[
"L_TYPE2"
]=>string(7)"Payment"[
"L_EMAIL0"
]=>string(26)"XXXXX%40hotmail%2ecom"[
"L_EMAIL1"
]=>string(31)"XXXX%40lvcoxmail%2ecom"[
"L_EMAIL2"
]=>string(23)"XXXXt%2ecom"[
"L_TRANSACTIONID0"
]=>string(17)"13E586955G649992Y"[
"L_TRANSACTIONID1"
]=>string(17)"8LH96897T3119113R"[
"L_TRANSACTIONID2"
]=>string(17)"87U867057E085230E"[
"L_STATUS0"
]=>string(9)"Completed"[
"L_STATUS1"
]=>string(9)"Completed"[
"L_STATUS2"
]=>string(9)"Completed"[
"L_AMT0"
]=>string(7)"85%2e00"[
"L_AMT1"
]=>string(7)"85%2e00"[
"L_AMT2"
]=>string(7)"85%2e00"[
"L_CURRENCYCODE0"
]=>string(3)"USD"[
"L_CURRENCYCODE1"
]=>string(3)"USD"[
"L_CURRENCYCODE2"
]=>string(3)"USD"[
"L_FEEAMT0"
]=>string(9)"%2d2%2e17"[
"L_FEEAMT1"
]=>string(9)"%2d2%2e17"[
"L_FEEAMT2"
]=>string(9)"%2d2%2e17"[
"L_NETAMT0"
]=>string(7)"82%2e83"[
"L_NETAMT1"
]=>string(7)"82%2e83"[
"L_NETAMT2"
]=>string(7)"82%2e83"[
"TIMESTAMP"
]=>string(28)"2012%2d11%2d08T14%3a24%3a30Z"[
"CORRELATIONID"
]=>string(13)"52c22d68648cd"[
"ACK"
]=>string(7)"Success"[
"VERSION"
]=>string(6)"51%2e0"[
"BUILD"
]=>string(7)"4137385"
}
I need to reset the array to just the following:
["L_STATUSn"]=>string(9)"Completed"
["L_TRANSACTIONIDn"]=>string(17)"8LH96897T3119113R"
with 'n' being the number, being the array key number that paypal returns.
Here is the code I am using, and it is borked.
$i = 0;
$c = 0;
foreach ($comparison AS $aKey => $v) {
$findme1 = 'L_TIMESTAMP'.$i++;
$findme2 = 'L_STATUS'.$c++;
$txid = $myarray[$findme1];
$status = $myarray[$findme2];
$TXid = array_search('$findme1', $aKey);
$Status = array_search('$findme2', $aKey);
$TxID[] = array('Status' => $aStatus, 'TransactionID' => $aTransactionID);
}
appreciate abetter way to reconstruct this array, the method I am trying to use doesnt appear to be too efficient.
Somewhat late, but maybe others have this request too. So here goes:
function process_response($str)
{
$data = array();
$x = explode("&", $str);
foreach($x as $val)
{
$y = explode("=", $val);
preg_match_all('/^([^\d]+)(\d+)/', $y[0], $match);
if (isset($match[1][0]))
{
$text = $match[1][0];
$num = $match[2][0];
$data[$num][$text] = urldecode($y[1]);
}
else
{
$text = $y[0];
// $data[$text] = urldecode($y[1]);
}
}
return $data;
}
Just feed the result from your curl call into this and take the result as a formatted array.
Note the commented out line, there are some fields that are global, such as version, if you want these, uncomment, but then you may have to adjust some formatting code down stream.
if you want to feed this into PHPExcel object, you could do so like so:
$index = 1;
foreach($data as $row)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$index, $row['L_TIMESTAMP'])
->setCellValue('B'.$index, $row['L_TIMEZONE'])
->setCellValue('C'.$index, $row['L_TYPE'])
->setCellValue('D'.$index, $row['L_EMAIL'])
->setCellValue('E'.$index, $row['L_NAME'])
->setCellValue('F'.$index, $row['L_TRANSACTIONID'])
->setCellValue('G'.$index, $row['L_STATUS'])
->setCellValue('H'.$index, $row['L_AMT'])
->setCellValue('I'.$index, $row['L_CURRENCYCODE'])
->setCellValue('J'.$index, $row['L_FEEAMT'])
->setCellValue('K'.$index, $row['L_NETAMT']);
$index++;
}

Need help with PHP homework - friend matching algorithm

I'm totally new to php and have started learning it. I have two homework assignments in php and html.
Assignment 1:
I have to store some people's names and all of their friends names. I have to list only people who have common friends. My problem is that if a person has no friends in common with someone else I get a message "Rana has 0 friends in common with Roni. I do I prevent this:
Assignment 2:
I have a html form to search for a person from the last php file
When I will search for Rana the PHP form will open and and print:
Rana have 4 friends and he has a common friend with Nandini and Mamun.
When I search for Tanmoy the page will be open and print:
Tanmoy is Rana’s friend who has 4 friends and common friends with Nandini and Mamun.
For this I have to used the function “post/get/request”
Here is my code so far:
<?php
# Function: finfCommon
function findCommon($current, $arr) {
$cUser = $arr[$current];
unset($arr[$current]);
foreach ($arr As $user => $friends) {
$common = array();
$total = array();
foreach ($friends As $friend) {
if (in_array($friend, $cUser)) {
$common[] = $friend;
}
}
$total = count($common);
$add = ($total != 1) ? 's' : '';
$final[] = "<i>{$current} has {$total} friend{$add} in common with {$user}.</i>";
}
return implode('<br />', $final);
}
# Array of users and friends
$Friends = array(
"Rana" => array("Pothik", "Zaman", "Tanmoy", "Ishita"),
"Nandini" => array("Bonna", "Shakib", "Kamal", "Minhaj", "Ishita"),
"Roni" => array("Akbar", "Anwar", "Khakan", "Pavel"),
"Liton" => array("Mahadi", "Pavel"),
"Mamun" => array("Meheli", "Tarek", "Zaman")
);
# Creating the output value
$output = "<ul>";
foreach ($Friends As $user => $friends) {
$total = count($friends);
$common = findCommon($user, $Friends);
$output .= "<li><u>{$user} has {$total} friends.</u><br /><strong>Friends:</strong>";
if (is_array($friends) && !empty($friends[0])) {
$output .= "<ul>";
foreach ($friends As $friend) {
$output .= "<li>{$friend}</li>";
}
$output .= "</ul>";
}
$output .= "{$common}<br /><br /></li>";
}
$output .= "</ul>";
# Printing the output value
print $output;
?>
For the assignment 1.1: You have just to filter out the unwantend responses with an
if ($total>0) {
$output .= "<li><u>{$user} has {$ ...
}
clause.
For the second assignment:
You have to create a page that expects a parameter to be read via $_GET or $_POST or $_REQUEST (call it name, for example). They are not functions, are arrays and you can access them from every scope in you program (they are superglobals and you don't need to declare them with gobals).
I would just print a select with the known people if the name (eg. $_REQUEST['name'] )is missing just print the form, otherwise find the person indicated by the input and print the result of the search.
EDIT:
For the second assignment, you will have to figure how to get the input data.
Probably I will use an approach a bit different
Provided that you have a form similar to this
<form action="homework.php" method="get">
Person: <select name="searchperson" />
<option> </option>
...
<option> </option>
</select>
</form>
you will have to get the list of all the known peoples in a manner similar to this:
$friends = array(
"Rana" => array("Pothik", "Zaman", "Tanmoy", "Ishita"),
"Nandini" => array("Bonna", "Shakib", "Kamal", "Minhaj", "Ishita"),
"Roni" => array("Akbar", "Anwar", "Khakan", "Pavel"),
"Liton" => array("Mahadi", "Pavel"),
"Mamun" => array("Meheli", "Tarek", "Zaman")
);
// create a flat array with all the known peoples
$knownPeople = array_reduce(
$friends,
function($current, $result) {
return array_merge($result, $current);
},
array_keys($friends)
);
$knownPeople = array_flip(array_flip($knownPeople)); //get rid of duplicates
asort(knownPeople); // sort the names
$knownPeople = array_values($knownPeople); // normalize the array indexes
and then get the form you need with a function like this:
function theForm($people) {
$options = '<option>'.join("</option>\n<option>",$people). '</option>';
echo "
<form action=\"homework.php\" method=\"get\">
<h2>Chose the people you want investigate on:</h2>
Person: <select name=\"person\" />
$options
</select>
</form>";
}
Whenever you get a grasp on the previous code or not, you have to evaluate the input and take the opportune actions:
Let say that your script is called homework.php (you will see the name into the action of the form) and it is located ad http://example.com. His URI will be http://example.com/homework.php
There are several possible scenarios:
the user call the script for the first time
the user choose a person from the select
the user invoke your script manually with a known person as parameter
the user invoke your script manually with a person you don't have in your list
Let's review the different cases:
the user call the script for the first time
What appened: the user go to http://example.com/homework.php crossing a link or writing the URI into the browser address bar.
How you detect this scenario: Given the form above you can check $_GET['person']. if it is not isset or empty or not array_key_exists you can state you are into the first scenario.
To do: Just output the form and exit.
the user choose a person from the select
What appened: the user get the form (first scenario) and choose a name from the select.
How you detect this scenario: The detection of the first scenario fails and you can find the name contained into $_GET['person'] into the knownPeople array.
To do:
sanitize the input (remove any spurious character)
find the name into the knownPeople array to be sure you are not serving a forged request
apply your functions to the person in input in order to get the desired output
output the result you got
the form for a new query or a link to http://example.com/homework.php
the user invoke your script manually with a known person as parameter
What appened: the user use a URI like http://example.com/homework.php?person=Rana to reach the script
How you detect this scenario: If the method you use in the form is get you can't (at least not using this simple scenarion) and you won't bother to as it can be considered a legal request as this is an homework and you don't have requirements about it. If you used the method post you have the chance to detect the forgeries as the parameter passed with that method are usually stored into the $_POST array. You can still find the name contained into $_GET['person'] into the knownPeople array.
To do: Same as second scenario
sanitize the input (remove any spurious character)
find the name into the knownPeople array to be sure you are not serving a forged request
apply your functions to the person in input in order to get the desired output
output the result you got
the form for a new query or a link to http://example.com/homework.php
the user invoke your script manually with a person you don't have in your list
How you detect this scenario: The detection of the first scenario fails and you can not find the name contained into $_GET['person'] into the knownPeople array.
To do:
sanitize the input (remove any spurious character)
find the name into the knownPeople array to be sure you are not serving a forged request
as the check fails output an error messages stating the user is unknown and let the user go to the correct uri with a link to http://example.com/homework.php.
Not all forgeries are bad. Consider an user that make a legal search and bookmark the result. If the list of friends change and then he returns to the page using the bookmark. He will fall straight into the fourth scenario
Hope this will help you to comprehend how the php scripting works.
change findCommon function from
function findCommon($current, $arr) {
$cUser = $arr[$current];
unset($arr[$current]);
foreach ($arr As $user => $friends) {
$common = array();
$total = array();
foreach ($friends As $friend) {
if (in_array($friend, $cUser)) {
$common[] = $friend;
}
}
$total = count($common);
$add = ($total != 1) ? 's' : '';
$final[] = "<i>{$current} has {$total} friend{$add} in common with {$user}.</i>";
}
return implode('<br />', $final);
}
to
function findCommon($current, $arr) {
$cUser = $arr[$current];
unset($arr[$current]);
foreach ($arr As $user => $friends) {
$common = array();
$total = array();
foreach ($friends As $friend) {
if (in_array($friend, $cUser)) {
$common[] = $friend;
}
}
$total = count($common);
$add = ($total != 1) ? 's' : '';
if ( $total > 0 ) $final[] = "<i>{$current} has {$total} friend{$add} in common with {$user}.</i>";
}
return implode('<br />', $final);
}
The change is i added a if ( $total > 0 ) before $final[] = ..
for the second one.
<?php
function searchPerson($person, $friends){
$direct = false;
$found = false;
if ( in_array ($person, array_keys($friends) ) ){
list($total, $common_friends) = commonFriend ($person, $friends);
$direct = true;
$found = true;
}
else{
foreach ( $friends as $friend => $his_friends ){
if ( in_array ( $person, $his_friends ) ){
list($total, $common_friends) = commonFriend ($friend, $friends);
$direct = false;
$found = true;
$friend_person = $friend;
break;
}
}
}
if ( !$found ) return false;
$output = $person . " ";
if ( $direct ){
$output .= " has " . $total . " friends";
}
else{
$output .= " is " . $friend_person . "'s friend who has " . $total . " friends";
}
if ( isset($common_friends[0]) ) $output .= " and common friends with " . $common_friends;
return $output;
}
function commonFriend ($person, $friends){
$my_friends = $friends[$person];
unset($friends[$person]);
$total_friends = count($my_friends);
$common_with = array();
foreach ( $friends as $friend => $his_friends ){
foreach ( $my_friends as $my_friend ){
if ( in_array ($my_friend, $his_friends) ){
$common_with[] = $friend;
}
}
}
$common_with = array_unique ($common_with);
$common_friends = "";
if ( count($common_with) > 0 ){
$common_friends = join (", ", $common_with );
}
return array ( $total_friends, $common_friends );
}
$friends = array(
"Rana" => array("Pothik", "Zaman", "Tanmoy", "Ishita"),
"Nandini" => array("Bonna", "Shakib", "Kamal", "Minhaj", "Ishita"),
"Roni" => array("Akbar", "Anwar", "Khakan", "Pavel"),
"Liton" => array("Mahadi", "Pavel"),
"Mamun" => array("Meheli", "Tarek", "Zaman")
);
$person = $_GET['person'];
$output = searchPerson($person, $friends);
if ( $output === false ) print $person . " is not on the list";
else print $output;
?>
What you have to do with the second assignment is you need a form.
lets say the above code was named searchPerson.php
then add a html page like
<html>
<head>
<title>Search for friend</title>
</head>
<body>
<form action="searchPerson.php" method="get">
Person: <input type="text" name="person" /><input type="submit" value="search" />
</form>
</body>
</html>
or run directly like
searchPerson.php?person=Rana
And why you get a message like that is because $person = $_GET['person']; gets the person name from the url, and u must have run it like searchPerson.php, so their is no value for $person to check.
-- EDIT
Chaged the code to work with people not in the list

Categories