I have the following codes:
$spaces=0;
$str="bike car ";
for($i = 0; $i < strlen($str); $i++)
{
if($str[$i]==" ")
{
$spaces+=1;
}
}
$names=explode(" ",$str);
The above code is used to split the words inside the string. How do i do a db query wherein i get the id of the names(words in the string i separated).
Assuming, i have a price table
The table has lets say 2 cols, item name and id
How do i parse DB query wherein i need to get the ids of the item names listed.
I guess you want to get the id of exploded $name simply you can use $this->db->where_in()
example :
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
See the documenation here : Where In Query
So the next line of your code maybe seems like this one :
$names = explode(" ",$str);
$this->db->select('id')
->where_in('your_table_name',$names);
$query = $this->db->get();
$result = $query->result_array();
then you can use the $result by
foreach($result as $r){
echo 'The id is :'.$r['id'];
}
You can simple use array_keys and array_values to traverse you array keys and values
//sample array
Array
(
[1334] => Face Towel
[4552] => White Socks
[3442] => Lotion
[6643] => Pants
[4432] => foobar
[5532] => bar
)
$items = implode(',',array_values($array)); //will get the array values
$itemid = implode(',',array_map('intval',array_keys($array))); //will get the array keys
$this->db->where_in('items', $items);
// where items IN ('Face Towel','White Socks','Lotion','pants','foobar','bar')
$this->db->where_in('itemid', $itemid);
// where itemid IN (1334,4552,3442,6643,4432,5532)
Note that i used array_map to loop through each keys and cast every key as integer.
Related
I have an array like this
$EN=array(
"text1"=>"translation1",
"text2"=>"translation2",
"text3"=>"translation3",
"text4"=>"translation4",
);
and this is my query
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN';";
$test= $conn->query($result);
The langVar column will retrieve text variables and the translation column is for translation words.
$EN=array(
foreach ($test AS $row){
$row['langVar']=>$row['$translation']
}
);
but it was a syntax error
Please, how can I do this the right way ?
You can't put a loop inside an array literal.
Add to the array inside the loop, not the other way around:
$EN = [];
foreach ($test as $row) {
$EN[$row['langVar']] = $row['translation'];
}
DEMO
You don't need a loop. If you only want to fetch all rows into a multidimensional array indexed by one of its columns, you cause use fetch_all() and array_column().
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN'";
$EN = array_column($conn->query($result)->fetch_all(), 0, 1);
I am trying to get data from a database that meets multiple criteria of an array.
The array is something like this:
Array ([21] => 1,[23] => 0,[19] => 1);
With the key being a Question ID and the values being either yes or no.
I need to find the movie where the value for question_id = 21 is 1, value for question_id = 23 is 0 and value for question_id = 19 is 1. The way I have them stored is like this:
So my first thought was get the data for each and then put them in a bigger array. If the movie shows up the same amount of times as the number of elements in the array, then I consider it a good match. But this seems inefficient. I would rather just find the movies that match the criteria.
Since there are movie_id records with the same value, is there a way to write something like this?:
foreach($array as $key=>$value){
$i++;
$this->db->where('question_id', $key);
$this->db->where('value', $value);
}
$this->db->from('movies_values');
$query = $this->db->get();
$res = $query->result();
array_push($main,$res);
The thought behind this is to create a loop of all the WHEREs. And then run the query using those where values. This doesn't seem to work, is there something else I can do?
How about using WHERE IN (array())?
From the CI User Guide:
$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')
Use the where_in method for lists:
$this->db->where_in('value', $array);
Try doing it like this.
$where = WHERE 1
foreach($array as $key=>$value){
$where .= " AND(question_id = $key AND value = $value)";
}
$this->db->where($where);
PS. What is the $i++ doing in your loop exactly?
I think this is the right way to go, you should take care to use "or" instead to use full "ands" that way would not return any row due to a logic problem (I mean question_id = 1 and value = 1 and question_id = 2 and value = 0 we're being inconsistent due to telling that we want question_id = 1 and question_id = 2 won't match nothing!, the same applies to "values").
$array = array(21 => 1,23 => 0,19 => 1);
$where = array();
foreach($array as $key => $value) {
$where[] = "(question_id=$key and value=$value)";
}
var_dump($where);
foreach ($where as $value) {
$this->db->or_where($value);
}
$q = $this->db->get('movies_values')->result();
var_dump($q);
echo $this->db->last_query();exit;
This can be done easily without loop:
$filter = array(21 => 1,23 => 0,19 => 1);
$values = implode(',',array_unique(array_values($filter))); // results into 0,1...
$keys = implode(',',array_unique(array_keys($filter))); // results into 19,21,23...
$result = $this->db
->query("select * from movies_values
where
question_id in(".$keys.")
and value in(".$values.")")
->result();
Happy coding ---> :)
I'm having major headaches trying to create a multidimensional array from two separate MySQL selects.... I've been searching here and Google all day and have to finally admit defeat and ask for some help (I'm a newbie as well which doesn't help!!!).
I have two tables, one which contains a single row result per id and another which can contain several rows for an id. What I'm trying to do is combine the two into a multidimensional array.
My code (poor as it may be) looks like this:
require 'php/phpConnection.php';
$sqlString1 = mysql_query("SELECT id FROM supportstaff_section1_a");
$firstArray = array();
$secondArray = array();
while ($r = mysql_fetch_assoc($sqlString1)) {
$applicantID = $r['id'];
$sqlString2 = mysql_query("SELECT educationalname FROM supportstaff_section5 WHERE id = '$applicantID'");
while ($x = mysql_fetch_assoc($sqlString2)) {
$secondArray[] = $x;
}
$firstArray[] = $r + $secondArray;
$secondArray = array();
}
print json_encode($firstArray);
mysql_close($con);
The result is this:
[{"id":"8m8wwy","0":{"educationalname":"GCSE - English"},"1":{"educationalname":"GCSE - Maths"}},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
But I think it needs to look something like this:
[{"id":"8m8wwy","Array2":"[{"educationalname":"GCSE - English"},{"educationalname":"GCSE - Maths"}]"},{"id":"wiL7Bn"},{"id":"zAw6M1"}]
Anyway, how can I insert my second SQL Select into my first SQL Select for each ID.
Thanks for any advice/help.
EDIT
Taken from W3Schools.com:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)
I'm trying to make it work like the above.
You need to get a little creative here. Something like the following would work as a join AND with multi-dimensional data:
<?php
require 'php/phpConnection.php';
// ======================================================================
// Create a join query (way faster than several separate ones!)
$sqlquery =
"SELECT SSSA.id, SSS5.educationalname" .
" FROM supportstaff_section1_a SSSA" .
" LEFT OUTER JOIN supportstaff_section5 SSS5 ON SSS5.id = SSSA.ID";
// ======================================================================
// Run the query and get our results
$resultarray = array();
if ($resource = mysql_query($sqlquery)) {
while ($curarray = mysql_fetch_assoc($resource)) {
// Create an array, if it doesn't exist
if (!isset($resultarray[$curarray["id"]]))
$resultarray[$curarray["id"]] = array();
// Add to the array, if not null
$curstring = (string) $curarray["educationalname"];
if ($curstring != "")
$resultarray[$curarray["id"]][] = $curstring;
}
mysql_free_result($resource);
}
// ======================================================================
// Convert from a keyed array to a standard indexed array (0, 1, 2, etc.)
$finalarray = array();
foreach ($resultarray as $id => & $data) {
// Start with just ID
$newarray = array(
"id" => $id
);
// Get the data, if we have any
if (count($data))
$newarray["educationalnames"] = & $data;
// Add to our final array and clear the newarray
$finalarray[] = & $newarray;
unset($newarray);
}
// ======================================================================
// Get the JSON of our result
$jsonresult = json_encode($finalarray);
// ======================================================================
// Echo it to test
echo $jsonresult;
// ======================================================================
// Close the database
mysql_close($con);
?>
And the resulting $jsondata would look like this (but not so unravelled of course):
[
{
"id": "8m8wwy",
"educationalnames": ["GCSE - English", "GCSE - Maths"]
},
{
"id": "wiL7Bn"
},
{
"id": "zAw6M1"
}
]
If you have an ID from the first Array, you can check for keys / values with this ID in the second Array.
If you want to get the key you should use
array_key_exists($string)
And if you want to get the value you should use
in_array($string)
You can use a foreach loop to execute this functions!
I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);
I have a table with entries such as:
123 (DVD)
123 [DVD] [2007]
125 [2009]
189 (CD)
when I present these to the user in an autocomplete field I do away with anything between either () or [] as these are not relevant, but, as you can see from the list above, that leaves me with two entries for 123 which appear in the dropdown... is there anyway to further suppress duplicates? Sometimes there can be as many as 5 or 6 which looks wrong to say the least! Code below:
// db select
$query = "SELECT $title FROM PRprodINFO2 WHERE ((prodcatID = '$cat_id') AND ($title LIKE \"%" . $_GET["q"] . "%\")) group by $title LIMIT 8";
$result = mysql_query($query);
$output_items = array();
// while loop to print results
while($row = mysql_fetch_array($result)) { $output_items[] = $row[$title]; }
$output_items = preg_replace('/\[.*?\]|\s*/', '', $output_items); // remove [blah]
$output_items = preg_replace('/\(.*?\)|\s*/', '', $output_items); // remove (blah)
print(implode("\n", $output_items));
Many thanks
The array_unique() function removes duplicate values from an array, in your case the $output_items array.
Take a look at http://php.net/manual/en/function.array-unique.php
You can use array_unique ( array $array ) to remove all duplicates before imploding.