get csv values from two coloumns mysql csv using php - php

enter image description here
Refer Image
I have values like this in mysql.
I need wholesaletl name based on wholesaletlcontact.
Example: when I have value ajin3 then i need the value 1234587452

Get the field values from db.
Explode them to an array.
$myString = "ajin1,ajin3,ajin2";
$myArray = explode(',', $myString);
print_r($myArray);
Do the same for the other field values.
Output will be: Array ( [0] => ajin1 [1] => ajin3 [2] => ajin2 )
Then get the id for a specific value:
$key = array_search('ajin3', $myArray);
And that Id will correspond to the required value in the other array.

Here could be the solution for you
$wholesaletl=explode(",",$record->wholesaletl);
$wholesaletlcontact=explode(",",$record->wholesaletlcontact);
$wholesaletlcontact_arr=array();
if(count($wholesaletl) > 0){
foreach($wholesaletl as $key => $value){
$wholesaletlcontact_arr[$value]=$wholesaletlcontact[$key];
}
echo $wholesaletlcontact_arr["ajin3"];

If you don't have a choice about using the csv files or if you don't feel that the drawbacks matter, the following code should help you with accessing the information:
function get_contact_from_name($name, &$name_array, &$contact_array) {
$name_index = array_search($name, $name_array);
// Name is not in csv list
if ($name_index === false) {
echo "Name does not exist: $name<br />";
return null;
}
// There is no contact in the corresponding postion
if (!isset($contact_array[$name_index])) {
echo "Contact does not exist at position: $name_index<br />";
return null;
}
return $contact_array[$name_index];
}
$names = 'bill,george,sophia,marge';
$wholesaleltnames = str_getcsv("bill,george,sophia", ",");
$wholesaleltcontacts = str_getcsv("123,456", ",");
foreach (explode(',', $names) as $name) {
$c = get_contact_from_name($name, $wholesaleltnames, $wholesaleltcontacts);
if ($c) {
echo "Contact: $name, $c<br />";
}
}
You will need to modify it to fit your needs. For example, it would need to be updated to use the row returned from mysql and to handle errors properly.

Related

Select one item from array

So, I wanna select item per item from this array ["A185","A740","A540"]
Like for example I wanna select
$cie[0] = A185 or A740
with something like $cie[0] = A185
This is my code so far, since I fetch that code from a row in a MySQL table.
while ($row = pg_fetch_array($resul)) {
$cie10 = array($row["cie"]);
}
$cie = ["A185","A740"];
$values = array_count_values($cie);
$top = array_slice($values, 0, 1);
print_r($top);
What I get:
Array ( [["A185","A740","A540"]] => 1 )
It just won't work.
I'm Sure you are looking to display the data that is in the array variable
$var = ["A185","A740","A540"]; // Asume as you stored the values in the array called var
foreach($var as $x){
print_r($x);
echo "<br/>";
}
EDIT: Highlighted the code
If i understand your problem. You are looking for this:-
$Fullarray = ["A185","A740","A540"];
$cie = array_slice($Fullarray,0,2);
foreach ($cie as $name) {
$d[] = '"' . $name . '"';
}
$implodekeys = "[".implode(',',$d)."]";
$newarray[$implodekeys] =1;
echo "<pre>"; print_r($newarray);
Hope it helps!

php how to push (accumulating) multidimensional array

Please, help with multidimensional array push. Please, see the code and comments below. The push is giving an error. The assigning is giving the last row only.
if (!isset($_SESSION['page_qstn_answer'])) {
$_SESSION['page_qstn_answer'] = array("page" => array(), "qstn" => array(), "answer" => array()
}
if (!isset($temp)) {
$temp = array("page" => array(), "qstn" => array(), "answer" => array() );
}
while($question = mysqli_fetch_assoc($question_set) ) {
if(isset($question['position']) ){
$post_qstn = $question['position'];
If(isset($_POST[$qstn]) ) {
//printing all rows from db correctly as below
//echo "Question ".$qstn." - selected answer ".$answer . " on page ".$page ."<br />";
if (isset($temp) ){
$temp = array ("page"=>$page, "qstn"=>$qstn,"answer"=> $answer);}
//show a one by one array rows correctly but $temp has a one row at a time that is Ok
//print_r($temp);
// Try to accumulate $temp into $_Session array. Push is giving an error
//$_SESSION['pages_qstn_answers'] = array_push($_SESSION['pages_qstn_answers'], $temp);
// No error but no accumulation as foreach as below shows the only one last row.
$_SESSION['pages_qstn_answers'] = $temp;
}
foreach ($_SESSION['pages_qstn_answers'] as $key => $value) {
echo "$key = $value\n";}
I used a function that I found on the website to delete all previously added the same questions before accumulating the $temp entries into the final array as there should be the only one question with a one answer. It seems a working. If somebody could see some shortcomings there please advise. Thanks
remove_elm($_SESSION['pages_qstn_answers'], "qstn", $qstn, TRUE);
$_SESSION['pages_qstn_answers'][] = $temp;
function remove_elm($arr, $key, $val, $within = FALSE) {
foreach ($arr as $i => $array)
if ($within && stripos($array[$key], $val) !== FALSE && (gettype($val) === gettype($array[$key])))
unset($arr[$i]);
elseif ($array[$key] === $val)
unset($arr[$i]);
return array_values($arr);
}
You have a misunderstanding of how array_push() works. It does not return the array, it just appends whatever value you have to it. So when you do:
$_SESSION['pages_qstn_answers'] = array_push($_SESSION['pages_qstn_answers'], $temp);
The right hand side of the equation simply returns an integer containing the number of elements in the new array. So say you now have 5 elements in your array, you are essentially doing
$_SESSION['pages_qstn_answers'] = 5;
Instead just do:
array_push($_SESSION['pages_qstn_answers'], $temp);
or since you're only appending one value I would stick with:
$_SESSION['pages_qstn_answers'][] = $temp;

How to fetch URL variable array using $_REQUEST['variable name']

I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}

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

How can I easily remove the last comma from an array?

Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.

Categories