I have a function:
function getDecision($num_players, $decisionType, $stage){
echo "in the function 1: ".$num_players."<br/>";
echo "in the function 2: ".$decisionType."<br/>";
echo "in the function 3: ".$stage."<br/>";
$x = mysql_query("
SELECT `decisionValue` FROM `teamdecision` WHERE `decisionType` = '$decisionType' && `period`= '$stage'
")or die($x."<br/><br/>".mysql_error());
$y = array();
$i="0";
while ($i<($num_players) && $row = mysql_fetch_assoc($x))
{
$y[$i] = $row['decisionValue'];
$i++;
}
return ($y);
}
Y will be populated with a number of values depending on the $num_players. I am calling the function as follows:
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
echo "Value = ".$value[$j][$i]."<br/>";
}
}
As you can see I am doing this wrong. I need to output the data located in $value however I am confused with how multi dimensional arrays work. I understand I need to read up on the subject, if possible can you point me to a suitable learning source?
So I changed up the code so that the following is being used to produce an output below:
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
echo "Value = ".$value[$j][$i]."<br/>";
}
}
I expected to output as follows:
$value[0] should contain $y which then contains each SUconsultant value. $value[1] should contain $y which then contains each marketT value and so on.
for ($i=0;$j<4;$i++){
should be
for ($j=0;$j<4;$j++){
And
$value[$i] = getDecision($num_players, $name[$i], $currentStage)."<br/>";
should be
$value[$j] = getDecision($num_players, $name[$j], $currentStage)."<br/>";
You have a $j in your first for loop, but setting and incrimenting $i in it. Maybe change them to $j as well.
EDIT
It actually looks like you have an issue with where you are returning the data:
echo "Value = ".$value[$j][$i]."<br/>";
This should be (it appears):
for ($f = 0; $f < $num_players; $f++){
echo "Value = ".$value[$i][$f]."<br/>";
}
Since you are currently on $value[$i] by the time you reach this point, then you need it to echo out one for each player.
This solution worked, after a lot of playing around it seems that the [] after of
the value array was also needed? At least I think so
$value = array();
$name = array();
for ($j=0;$j<$num_players;$j++){
for ($i=0;$i<4;$i++){
$name[0] = "SUconsultant";
$name[1] = "marketT";
$name[2] = "sector";
$name[3] = "saleprice";
echo $name[$i]."<br/>";
$value[] = getDecision($num_players, $name[$i], $currentStage);
//echo "Value = ".$value[$i]."<br/>";
echo "<br/><hr/>";
echo "Value = ".$value[$i][$j]."<br/><hr/>";
}
}
Output:
And now I have changed to:
$value[] = getDecision($num_players, $name[$i], $currentStage);
echo "Team ".$j." ".$name[$i]." = ".$value[$i][$j]."<br/>";
To get my eventual goal of:
Related
I've got something I think it is a 3 dimensional array:
$var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172';
So there are 2 arrays packed inside the variable. First is separated by | the second one by ,
What I need to do is: separate them and then check for an ID located before the name and give me single variables of the rest.
I tried it like this:
<?php
$personid = 3;
$var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172';
$array = explode('|',$var);
foreach($array as $values) {
$arr = explode(",",$values);
foreach($arr as $value) {
if($value[0] == $personid) {
$id = $value[0];
$name = $value[1];
$height = $value[2];
$killloop = 1;
}
}
if($killloop == 1) {
break;
}
}
echo 'ID: '.$id.'<br> Name: '.$name.'<br> Height: '.$height;
?>
But all i get then is:
ID: 3
Name:
Height:
Can anyone help out?
There is no need loop Into Second Array, You already have defined positions.
Always Use break statement to end a Loop immediately, Its a good practice
<?php
$personid = 3;
$var = '1,Tony,186|2,Andrea,163|3,Peter,178|4,Sally,172';
$array = explode('|',$var);
foreach($array as $values) {
$arr = explode(",",$values);
if(!empty($arr) && $arr[0] == $personid){
$id = $arr[0];
$name = $arr[1];
$height = $arr[2];
break;
}
}
echo 'ID: '.$id.'<br> Name: '.$name.'<br> Height: '.$height;
?>
I'm making a rather simple search engine with PHP and I've ran into a problem... The engine will only work for one SQL row. In the table the PHP is connected to, there are two rows. One named "The Painful Truth" and the other "Darkness Rising". If you type "darkness" or "rising" into the search bar it will come back with "Darkness Rising" as expected. However, if you input "the", "painful", or "truth" into the bar it will come back with zero results.(P.S. "The Painful Truth" is the first entry in the table) I attempted to debug it by listing out the song names in the table, the search, and the array after exploding the song names. They all line up like they should work, but alas, they don't.
The code below takes the input and removes characters and spaces
$lower = strtolower($_POST["text"]);
$characterRemover = preg_replace('/[^ \w]+/', '', $lower);
$search = str_replace(' ' , '' , $characterRemover);
echo "<strong>". $search . "</strong><br>";
The code below takes data from the database, explodes the string and tries to find a match.
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
} else {
$song_result = "0 results buddy";
}
}
here's how it looks when I search for "the":
What's happening here is that the loop is running for every single row and the variable $song_result is being overwritten. Try to use a flag $found to get the song.
$found = false;
while(!$found && ($row = $result->fetch_assoc())) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$song_result = $row["song_name"];
$found = true;
} else {
$song_result = "0 results buddy";
}
}
If you want to capture every song, then use an array or concatenate a string:
$songs = [];
while($row = $result->fetch_assoc()) {
$Slower = strtolower($row["song_name"]);
echo "Song Name: " . $Slower . "<br>";
$song_name = explode(" " , $Slower);
// list array
$arrlength = count($song_name);
for($x = 0; $x < $arrlength; $x++) {
echo $song_name[$x];
echo "<br>";
}
if (in_array($search, $song_name) !== false) {
$songs[] = $row["song_name"];
}
}
if (count($songs)) {
$song_result = implode('<br>', $songs);
} else {
$song_result = "0 results buddy";
}
Note: You should follow JimL's suggestion and request the info filtering the DB query via the WHERE clause. And then just show the result of the query. ;)
<?php
//Kindly make sure you have create a connection and select a db. this is a sample code to search from mysql db using data supplied
$msg=$_POST['search'];
if(isset($msg)){
$search=explode(' ',$msg);
$len=count($search);
$query="select * from news where ";
for($m=0;$m<$len;$m++){
$query.=" post like '%{$search[$m]}%' || ";
}
$query.=" post like '%{$msg}%' order by upload_date desc";
if($get=mysqli_query($connect,$query)){
$contentSearch=array();
$i=0;
while($row=mysqli_fetch_assoc($get)){
contentSearch[$i]=$row;
$i++;
}
echo"List of Search Items<br>";
print_r($contentSearch);
}
}
I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}
I am having a real issue with variable interpolation - maybe what I'm trying to do shouldn't be done? Sample code (IRL, the array is 70+ elements):
<form submit>
$_POST['A']; //returns 12
$_POST['B']; //returns 8
<query to get orig field values>
$OrigA = $row->appA; //returns 12
$OrigB = $row->appB; //return 14
<array of names>
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$new = "\$_POST['app" . $field . "']";
$fieldname = "app" . $field;
if (${$orig} != ${$new}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
The part if (${$orig} != ${$new}) is what's not working as I would expect. When I print it out to screen with print "DEBUG: if (${$orig} != ${$new}) { $querystr .= \"('default', $applID, '$fieldname', '{$orig}', '{$new}', '$DateTimeReq', '$hvid')\"; };<br />\n";, I see my variables aren't interpolating properly, my debug print says: DEBUG: if ( != ) { .... It should interpolate to (for B): DEBUG: if (8 != 14) { ...
I have tried various combinations of dollar signs and braces, but I don't seem to be making headway. Am I barking up the wrong tree here?
Thanks as always!!
Like this : No interpolation POST variable
<?php
$A = $_POST['A'] = 12; //returns 12
$B = $_POST['B'] = 8; //returns 8
$OrigA = 12; //returns 12
$OrigB = 14; //return 14
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$fieldname = "app" . $field;
if (${$orig} != ${$field}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
?>
See http://codepad.org/Ecro0PyG
I don't get all your questions but maybe this code could help you a little (you can use your $_POST var instead of mine $post, that is just to show result and debug):
$post = array();
$post['A'] = 12;
$post['B'] = 8;
$OrigA = 12;
$OrigB = 14;
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$origVarName = 'Orig'.$field;
echo '$$origVarName = '.$$origVarName.'<br/>';
echo '$post[$field] = '.$post[$field].'<br/>';
$fieldname = "app" . $field;
if ($$origVarName != $post[$field]) {
echo $field.' NOT EQUAL!';
} else {
echo $field.' EQUAL!';
}
}
Here is the problem : I want to split a string to have the name and the first name, but my two variable are empty and i don't understant why... Can someone help me ? This my code :
$nom_aut1 = "";
$prenom_aut2 = "";
//$auteur1 is already initialized
for ($i = 0; $i < strlen($auteur1); ++$i)
{
if ($auteur1[$i] != ' ') continue;
for ($j = 0; $j < $i; ++$j)
{
$nom_aut1 .= $auteur[$j];
}
for ($j = $i+1; $j < strlen($auteur1); ++$j)
{
$nom_aut1 .= $auteur1[$j];
}
break;
}
echo '"'.$nom_aut1.'.'.$prenom_aut1.'"';
Thank you :)
Do you want to split a name into first and last name based on a space? Why not just do this:
$names = explode(" ",$name);
If $name = "Hello World"
$names will be an array such that
$names[0] = "Hello"
$names[1] = "World"
This way, if there is a middle name, you can get that as well.
You can do it this way:
$names = explode(" ",$name);
if (count($names) == 1) //only first name
{
$first = $names[0];
$last = "";
}
else if (count($names) == 2) //only first and last name
{
$first = $names[0];
$last = $names[1];
}
else //one or more middle names were provided
{
$first = $names[0];
$last = $names[count($names)-1];
for($i=1;$i<count($names)-1;$i++)
$middle .= $names[$i] . ' ';
$middle = trim($middle);
}
So, if $name = "Hello Foo Bar World"
$first = "Hello"
$last = "World"
$middle = "Foo Bar"
If the letter is not equal to ' ' it continue the loop and does not execute the 2 for loops.
But you are looking for the explode function in PHP:
<?php
$names = explode(' ', $name);
$prenom = $names[0];
$nom = $names[1];
?>
First of all, double check all your variable names.
You are saying:
$nom_aut1 = "";
$prenom_aut2 = "";
You are not using $prenom_aut2 anywhere in your code and then you are echoing:
echo '"'.$nom_aut1.'.'.$prenom_aut1.'"';
In answer to your specific question, you are declaring, populating and echoing different variables.
Another way to explode and manipulate this way!.
list($first_name, $last_name) = explode(" ", $name);
echo $first_name;
echo $last_name;