I have a bizarre issue that I cannot for the life of me seem to resolve.
I am generating an array ($tags) from a mysql query, it looks something like this:
Array(
[1] => Safety Toe
[2] => Waterproof
)
Then I have another array ($link) I generate in a loop:
Array(
[1] => Array(
[0] => 1
[1] => 2
)
[2] => Array(
[0] => 1
[1] => 2
)
)
Also, I have 2 predefined variables that in this case are as follows:
$max == 2;
$title_count == 3;
Later on I have 2 for loops, 1 is nested:
for($y=0;$y<$max;$y++){
for($x=1;$x<=$title_count;$x++){
if($x==1){
echo "<tr><td>".$tags[$link[$x][$y]]."</td>";
}elseif($x<$title_count){
echo "<td>".$tags[$link[$x][$y]]."</td>";
}else{
echo "<td>".$tags[$link[$x][$y]]."</td></tr>";
}
}
}
This should produce something along the lines of:
Safety Toe Safety Toe Safety Toe
Waterproof Waterproof Waterproof
The problem is this is what I get:
Safety Toe Safety Toe Safety Toe
This made me curious, so I tried manually inputting $tags[2]. That worked and produced:
Waterproof Waterproof Waterproof
Waterproof Waterproof Waterproof
However, if I manually set them all to $tags[$link[1][1]] ($link[1][1] == 2) I get an empty result. If I set a variable, such as $test = $link[1][1]; (which echoes as 2), and then try $tags[$test], I get nothing. However if I set $test = 2; and do $tags[$test] I get Waterproof.
I am beyond bewildered here, if there is anything I'm missing, or any ideas as to why this would be the way it is, please let me know.
Thanks!
I figured out my problem, and it would not have been determinable from what I posted.
I tested
$tags[intval($links[1][1])]
and it worked.The $links array is being generated by exploding a string (1, 2). I was axploding on "," not ", " so the value of the second entry was " 2" instead of "2", hence the intval.
The string needs to be adjusted to "1,2" or the explode needs to be adjusted to ", ". Either way fixes the problem.
Related
I'm wanting to replace the first character of a string with a specific character depending on its value,
A = 0
B = 1
C = 2
Is there a way to do this based on rules? In total I will have 8 rules.
Ok, so I'm editing this to add more information as I don't think some people understand / want to help without the full picture...
My string will be any length between 5 and 10 characters
Capitals will not factor into this, it is not case sensitive
Currently there is no code, I'm not sure the best way to do this. I can write an if statement on a substring, but I know straight away that is inefficient.
Below is the before and after that I am expecting, I have kept these examples simple but all I am looking to do is replace the first character with a specific character depending on its value. For now, there are eight rules, but this could grow in the future
INPUT OUTPUT
ANDREW 1NDREW
BRIAN 2RIAN
BOBBY 2OBBY
CRAIG 3RAIG
DAVID 4AVID
DUNCAN 4UNCAN
EDDIE 5DDIE
FRANK 6RANK
GEOFF 7EOFF
GIANA 7IANA
HAYLEY 8AYLEY
So as you can see, pretty straight forward, but is there a simple way to specifically specify what a character should be replaced by?
Assuming all the rules are for single characters, like in the example, it would be easisest to code them in to a dictionary:
$rules = array('A' => 0, 'B' => 0 /* etc... */);
$str[0] = $rules[$str[0]];
I think this is what you want.
<?php
$input = array('ANDREW','BRIAN','BOBBY','CRAIG','DAVID','DUNCAN','EDDIE','FRANK','GEOFF','GIANA','HAYLEY');
$array = range('A','Z');
$array = array_flip(array_filter(array_merge(array(0), $array)));
$output = [];
foreach($input as $k=>$v){
$output[] = $array[$v[0]].substr($v, 1);
}
print_r($output);
?>
Output:
Array (
[0] => 1NDREW
[1] => 2RIAN
[2] => 2OBBY
[3] => 3RAIG
[4] => 4AVID
[5] => 4UNCAN
[6] => 5DDIE
[7] => 6RANK
[8] => 7EOFF
[9] => 7IANA
[10] => 8AYLEY
)
DEMO: https://3v4l.org/BHLPk
EDIT: Alright, my original post was kinda confusing, I've also tried something new. Here's my code:
if($_POST['submit']=='Save'){
$_SESSION['quantity'] = $_POST['quantity'];
$_SESSION['order'] = array_combine($_SESSION['parts-order'], $_SESSION['quantity']);
header("Location: shopping.php");
exit;
}
Both $_SESSION arrays are 430 long, both containing strings. When I print_r() on both $_SESSION arrays separately, they return their expected values. Basically, when I combine the arrays, I expect this output:
Array
(
[1 inch ratchet tie down] => 13
[24" White Ring Buoy w/ Reflective Tape] => 4
[50' Throw Line w/bag] => 5
[Classic Shirt Large] => 0
...
)
Y'know, or whatever values are in $_SESSION['quantity']. I, instead, get this:
Array
(
[1 inch ratchet tie down] => 0
[24" White Ring Buoy w/ Reflective Tape] => 0
[50' Throw Line w/bag] => 0
[Classic Shirt Large] => 0
...
)
Unless each of the $_SESSION['quantity'] values is the same, it produces 0. How do the values get changed to 0 in the process of array_combine?
Thanks.
Hi guys I have been trying to do this for sometime. Would you please give me an insight on how to go about this.
I have a text file containing questions and their respective multiple choice answer spaced using space bar between each element.
I have been able to read and put the text file lines into arrays. But now what has prooved difficult to achieve is how to put each and every element to an html form element. these are my codes:
Text file:
Number Question (a) (b) (c) (d)
1 The most important feature of spiral model is requirement analysis. risk management. quality management. configuration management.
2 The worst type of coupling is Data coupling. control coupling. stamp coupling. content coupling.
3 One of the fault base testing techniques is unit testing. beta testing. Stress testing. mutation testing.
4 A fault simulation testing technique is Mutation testing Stress testing Black box testing White box testing
5 RS is also known as specification of White box testing Stress testing Integrated testing Black box testing
The page that reads the text file:
`html>
<head>
<title>read</title>
</head>
<body>
<b><u> QUESTIONS AND ANSWERS QUIZ</u></b <br />
<p>
<?php
$openFile = fopen("questionandanswers.txt", "r") or exit ("unable to open the text file");
$fileContents = fread($openFile, filesize("questionandanswers.txt"));
fclose($openFile);
$delimiter = " ";
$myArray = explode($delimiter, $fileContents);
print_r($myArray);
?>
</p>
</body>
</html>`
THe print_r displays the following:
Array ( [0] => Number [1] => Question [2] => (a) [3] => (b) [4] => (c) [5] => (d) 1 [6] => The most important feature of spiral model is requirement analysis. [7] => risk management. [8] => quality management. [9] => configuration management. 2 [10] => The worst type of coupling is [11] => Data coupling. [12] => control coupling. [13] => stamp coupling. [14] => content coupling. 3 [15] => One of the fault base testing techniques is [16] => unit testing. [17] => beta testing. [18] => Stress testing. [19] => mutation testing. 4 [20] => A fault simulation testing technique is [21] => Mutation testing [22] => Stress testing [23] => Black box testing [24] => White box testing 5 [25] => RS is also known as specification of [26] => White box testing [27] => Stress testing [28] => Integrated testing [29] => Black box testing )
You explode() using space as separator, that's why you are getting each word as an array element. explode() just uses the character you give it and split the string whenever it encounters the character.
Your data (the file) hasn't got a pattern. So you need to stablish some rules in the text, or you won't be able to separate the information you want:
I modified your text stablishing some rules:
The questions will be finished with a colon(:).
The answers will be finished with a dot(.), all of them but the last one, as we will use the number of the question as separator.
The questions or answers won't contain any numbers [0-9] or it will confuse the regex.
This is the resulting text I modified manually to make the text work:
$string = 'Number Question (a) (b) (c) (d) 1 The most important feature of spiral model is: requirement analysis. risk management. quality management. configuration management 2 The worst type of coupling is: Data coupling. control coupling. stamp coupling. content coupling 3 One of the fault base testing techniques is: unit testing. beta testing. Stress testing. mutation testing 4 A fault simulation testing technique is: Mutation testing. Stress testing. Black box testing. White box testing 5 RS is also known as: specification of White box testing. Stress testing. Integrated testing. Black box testing';
The solution:
After that we can use some code to separate the information:
<html>
<head>
<title>read</title>
</head>
<body>
<b><u> QUESTIONS AND ANSWERS QUIZ</u></b> <br />
<?php
$openFile = fopen("questionandanswers.txt", "r") or exit ("unable to open the text file");
$string = fread($openFile, filesize("questionandanswers.txt"));
//Regex to get from the first number to the string's end, so we ignore the Number Question... bit;
preg_match('/\d.*/', $string, $match);
//We get all the strings starting with a number until it finds another number (which will be the beginning of another question;
preg_match_all('/\d\D*/', $match[0], $results);
$qas = array(); // We prepare an array with all the questions/answers
foreach($results[0] as $result){
//Separating the answer from the string with all the answers.
list($question, $all_answers) = explode(':', $result);
//Separating the different answers
$answers_array = explode('.', $all_answers);
//Stuffing the question and the array with all the answers into the previously prepared array;
$qas[] = array('question' => $question, 'answers' => $answers_array);
}
//Looping through the array and outputting all the info into a form;
foreach($qas as $k => $v){
echo "<label>{$v['question']}</label><br/>";
echo "<select>";
//we loop through $v['answers'] because its an array within the array with all the answers.
foreach($v['answers'] as $answer){
echo "<option>$answer</option>";//the output
}
echo "</select>";
echo "<br/><br/>";
}
?>
</body>
</html>
Looks complex because of all the comments, they are less than 20 lines of text actually
You can see the output here: output
Notes
Did this just to practice, but next time try to research more, and ask specific questions, or people will ignore/downvote your, have a good read about the Stackoverflow's FAQs
You should format your array into a multidimensional one, where the index 0 is the question:
Array
(
[0] = array
(
[0] = "This is the first question";
[1] = "Answer A";
[2] = "Answer B";
)
[1] = array
(
[0] = "This is the second question";
[1] = "Answer A";
[2] = "Answer B";
[3] = "Answer C";
)
)
You can now include it the following way:
<form>
<?php
foreach($filecontent as $question)
{
echo '<p>' .$question[0] .'</p>';
for($i = 1; $i < count($question); $i++)
{
echo '<input value="' .$question[$i] .'" />';
}
}
?>
</form>
I'm using the Nestoria API to retrieve property results.
Everything is working quite well and one can return up to 50 properties using this method.
I would like to show 10 items at a time and allow for the user to paginate through them, but for some reason I'm having difficulty doing this.
The code snippet around the section that controls this is as follows:
$page = isset($_REQUEST["page"]) ? (int)$_REQUEST["page"] : 1;
$page = $page-1;
$pagination = new pagination;
$propertyResults = $pagination->generate($nestoria->decodedData->response->listings, 10);
foreach($propertyResults as $listing) {
//do stuff
}
A snippet of the data array would be:
Array
(
[0] => stdClass Object
(
[auction_date] =>
[property_type] => house
[summary] => Located in North Kingston a two double bedroom Victorian house presented in...
[title] => York Road, Kingston, KT2 - Reception
[updated_in_days] => 6.5
[updated_in_days_formatted] => this week
)
[1] => stdClass Object
(
[auction_date] =>
[property_type] => house
[summary] => Fine home was built about 50 years ago and enjoys one of the best locations...
[title] => Coombe Hill, KT2 - Conservatory
[updated_in_days] => 2.5
[updated_in_days_formatted] => this week
)
....
(sample cut down due to size of array elements)
Now I have been staring at this for way too long now and I've drawn a blank.
This code works correctly except if I try go to any other page other than 1, then the page doesn't finish loading, it just carries on until Firefox says: "The page isn't redirecting properly".
So basically, pagination is able to cut my data array up correctly, but is failing to "paginate" correctly.
Any help?
Turns out the problem with the redirect was actually an .htaccess issue which was using the $_GET["page"] variable and was therefore getting confused, so I renamed all references to the $_GET["page"] to $_GET["_page"] in this app.
I have mysql search results from a keyword search being performed on my site. They're sorted by membership rank (0-3). However, I need to display the ranks differently than each other - like rank 3 gets more prominent formatting than the others.
I was thinking of splitting the rows up into individual arrays. So like array0 would contain all the rows that had the rank of 0, etc. Then loop through these arrays to display the results. I just have NO idea how to do this -- split the array up into smaller arrays.
(For reference, I found this question: splitting a large array into smaller arrays based on the key names but I wasn't really sure if that's what I needed... maybe some clarification on that q would help here?)
For example here is my array:
Array (
[rank] => 3
[organization] => Test Company
[imagecompany] => 1636.gif
[website] => http://www.google.com
[phone] => 344-433-3424
[fax] =>
[address_on_web] => physical
[address] => 2342 Test Ave
[city] => York
[stateprov] => WA
[postalcode] => 00000
[address_mailing] => 2342 Test Ave
[city_mailing] => Seattle
[state_mailing] => WA
[zip_mailing] => 00000
[description] => 'Test test Test test Test test Test test Test
test Test test Test test Test test Test test Test test Test test Test test Test test
Test test Test test'
[customerid] => 1636 )
You can use the rank as a key to create an multidimensional array like this:
$aRanks = array();
foreach($aArray as $aEntry) {
$aRanks[$aEntry['rank']][] = $aEntry;
}
echo '<pre>';
print_r($aRanks);
I have mysql search results from a keyword search
Then sort it using the database/SQL - not PHP. It's faster and uses less code.
$query = mysql_query(); // your query here
$result = mysql_fetch_array($query);
foreach($result as $row){
switch($row['rank']){
case 3:
// statement to apply formatting, add to each case
// example:
echo "<span style="color:red;">;
break;
case 2: break;
case 1: break;
}
}
Then output each row, echo closing </span> (or div or whatever) where you want the formatting to end