I have a SQL query which returns a result of one field, so I have the following:
$article_id = $this->item->id;
$authors_default = mysql_query("SELECT multi_authors FROM jos_jxzine_articles WHERE id = '$article_id' LIMIT 1");
$authors_default = mysql_fetch_assoc($authors_default);
echo $authors_default['multi_authors'];
This echos out
128,129
and so on for different queries.
How can I make this into the following
array(128,129)
To then put into a prewritten function?
Cheers
The following code takes that MySQL row and splits it up into pieces using , as the delimiter. It then converts that array of strings to an array of integers.
$authors_arr = explode(',', $authors_default['multi_authors']);
// $authors_arr = array("128", "129");
$authors_arr = array_map('intval', $authors_arr);
// $authors_arr = array(128, 129);
You can then pass that array into a function like so:
myFunction($authors_arr); // Or however you have it setup.
$authors_array = explode(",", $authors_default['multi_authors']);
This will break apart your MySQL result into an array. Since your query pulls a string which is delimited by a comma, the explode() function can be used to separate out the string.
http://php.net/manual/en/function.explode.php
Sorry, this is untested since I have removed PHP from my localhost. If I understand you correctly.
<?php $arr = explode(',', $authors_default['multi_authors']); print_r($arr); ?>
http://php.net/manual/en/function.explode.php
Related
I have a string that looks like this
$genres = "pop,rock,jazz,80s";
i was wondering is it possible to then create a string that randomly selects any of those genres above? but removing the comma?
for example it would create
$newgenre = "pop";
You could use something like this:
$genreArray = explode(',', $genres);
$genre = $genreArray[mt_rand(0, count($genreArray))];
Alternative Method
Everyone else is using random selection from an array, try this alternative:
$genreArray = explode(',', $genres);
shuffle($genreArray); //mixes up the array using rand or mt_rand
$genre = $genreArray[0]; // take first element of shuffled array.
You can use the $genreArray = explode(',', $genres) function to put it all into an array.
Then you can generate a random index for the array, using
$randomKey = rand(0, count($genreArray))
And then, all you have to do is take the random genre from the array.
$randomGenre = $genreArray[$randomKey];
You could explode
and get a random value from the array
$genresArray = explode(',',$genres);
$your_values = array_rand ($genresArray,1);
echo $your_values[0];
I'm successfully scraping a website to get space separated data off of the page:
$html = file_get_contents("http://www.somewebsite.com");
$scores_doc = new DOMDocument();
$scores_doc->loadHTML($html);
$scores_path = new DOMXPath($scores_doc);
$scores_row = $scores_xpath->query('//td[#class="first"]');
foreach($scores_row as $row){
echo $row->nodeValue . "<br/>";
}
Example output:
23 Crimmons, Bob (CA)
48 Silas, Greg (RI)
82 Huston, Roger (TX)
21 Lester, Terry (NC)
Instead of printing the output using 'echo' I need to split the value into four smaller pieces and into variables (array or otherwise). I know the MySQL side very well, I just don't use PHP day to day. I tried (in place of the 'echo' and after defining it as an array):
$data[] = echo $row->nodeValue;
A sidenote on the used syntax:
If you just want to assign the whole 23 Crimmons, Bob (CA) string as one string to an array. You should use the right syntax.
$data[] = echo $row->nodeValue;
Should be:
$data[] = $row->nodeValue;
Three possible solutions to your problem.
Solution 1: Improve scraping
The best way to scrape those four values seperately would be to query more specifically. You can try to update your xpath query on line:
$scores_xpath->query('//td[#class="first"]');
The query you can use depends on the structure of the page you're scraping.
Solution 2: Splitting string using PHP explode
You could use PHP's explode function to separate the string, but note that will give some problems when there are spaces used in a name.
echo $row->nodeValue . "<br/>";
Can be something like:
// Assuming that $row->nodeValue will have the string `23 Crimmons, Bob (CA)` as it's value
$explodeRow = explode(' ', $row->nodeValue);
/*
* $explodeRow now contains four values.
*
* $explodeRow[0] = "23";
* $explodeRow[1] = "Crimmons,";
* $explodeRow[2] = "Bob";
* $explodeRow[3] = "(CA)";
*/
You can choose to remove the ( and ) characters in $explodeRow[3] with the PHP str_replace, preg_replace or substr function for example.
Solution 3: Splitting string using regular expressions
Alternatively you can decide to fetch the first two numbers first. Then to fetch the last part between (). Then seperate the two remaining values by ,. But this can also generates problems when multiple commas are used.
Example of this solution will be, something like:
preg_match("~^(\d+)~", $row->nodeValue, $number);
$number[1]; # will be 23
preg_match("#\((.*?)\)#", $row->nodeValue, $last);
$last[1]; # will be CA
$middleExp = explode("(", $row->nodeValue, 2);
$middle = substr((strlen($number[1])-1), strlen($row->nodeValue), $middleExp[0]);
$middleExp2 = explode(",", $middle);
$middleL = $middleExp2[0]; # will be Crimmons
$middleR = $middleExp2[1]; # will be Bob
I'm using this to to retrieve two columns in a database
while($comment[]=mysql_fetch_array($sql));
this returns an array with associative and number indices for each column.
This works great but I would also like to create a new array from the orginial$comment[] that is just a simple array of strings (only the first column). What are my options? Is there any way to accomplish this without looping through a second time?
Depending on how many columns you have, you could do something like:
$result = mysql_query($sql);
while (list($col1[], $col2[]) = mysql_fetch_row($result));
$col1 will be an array of just column 1's values, and $col2 will be similar for column 2's values.
$array = array();
for ($i = 0;$comment = mysql_fetch_array($sql);$i++){
$array[$i] = $comment['field_name'];
}
I have a script that will insert a value in a cell, in my database. That cell will contain 4 values total. It should look like this: 0;0;0;0 (Each '0', represents a value)
How can I insert example value 100, at the place where '0' number 3 is, so it will look like this:
0;0;100;0
Thanks in advance.
This is bad database design and breaks the first normal form of database design.
I would recommend re-thinking your schema and data architecture.
Maybe break them out into individual columns.
Your data should be designed relationally to minimize repeating patterns in your columns (see link above)
I can almost guarantee you that there is a better way...
look into serialize() and unserialize()
$array = array(0,20,103,330);
$string = serialize($array); // store this in db
then get the string from db:
$array = unserialize($string);
access/update values with the array and re-store in db
Or if you are stuck with the format:
$string = '0;0;100;0'; // coming from db
$array = explode(';' , $string);
$array[2] = 100;
$string = implode(';' , $array);
<?php
// original string of values seperated by colon
$string = "0;0;0;0";
// create array of values by splitting at colons
$vals = preg_split('/;/', $string);
// modify the value of any elements in your array
$vals[2] = 100;
// glue your array of values together with semicolons at the joins
$string = implode(';',$vals);
// check the value has been changed coreectly
echo $string;
?>
By example:
FirstString='apple,gold,nature,grass,class'
SecondString='gold,class'
the Result must be :
ResultString='apple,nature,grass'
$first = explode(',',$firstString);
$second = explode(',',$secondString);
Now you have arrays and you can do whatever you want with them.
$result = array_diff($first, $second);
this is the easy way (for sure there must be more efficient ones):
First of all, you may want to separate those coma-separated strings and put them into an array (using the explode function):
$array1 = explode(',' $firstString);
$array2 = explode(',' $secondString);
Then, you can loop the first array and check whether it contents words of the second one using the in_array function (if so, delete it using the unset function):
// loop
foreach( $arra1 as $index => $value){
if( in_array ( $value , $array2 ) )
unset($array1[$index]); // delete that word from the array
}
Finally, you can create a new string with the result using the implode function:
$result = implode(',' , $array1);
That's it :D
I'm sure there is a function that can do it but you could always break up the strings and do a foreach on each one and do some string compares and build a new string. You could also break apart the second string and create a regular expression and do a preg_replace to replace the values in the string.