$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields
FROM categories
WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field = str_replace("/","",$field); /* Delete all '/' */
print_r($field);
}
Inside foreach loop, my query returns something like that /7/,/13/,/24/ from fields for every turn, then I clean them from slashes and commas.
My goal is collect all that arrays inside one array.
I tried to create an empty array outside of foreach and sum all in it but it returned empty.
You have to be define $filed as a array before foreach loop. now you can store value into $filed. note that you have to multidimensional array required to store value.
$cats_array = array(1,7,28);
$field = array();
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field1 = explode(",", $cat_field->fields); /* Explode ',' from '/'3'/,' */
$field[] = str_replace("/","",$field1); /* Delete all '/' */
}
print_r($field);
I don't understand why do you store the fields like that, but here is a possible solution:
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id = $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
preg_match_all('/\/(\d+)\//', $cat_field->fields, $matches);
if (!empty($matches[1])) {
$fields = array_merge($fields, $matches[1]);
}
}
print_r($fields);
$fields = array();
$cats_array = array(1,7,28);
foreach ($cats_array as $category) {
$category_field_query = "SELECT fields FROM categories WHERE status = 1 AND id= $category";
$category_field_query_run = mysqli_query($connect, $category_field_query);
$cat_field = mysqli_fetch_object($category_field_query_run);
$field = explode(",", $cat_field->fields); // Explode ',' from '/'3'/,'
$field = str_replace("/", "", $field);
$fields[] = $field;
}
print_r($fields);
Related
I am using three tables and one query in mysql in order to retrieve a particular user.
I am getting exactly what I want from the query, but it's not formatted in the right way.
My query:
public function get_all_payslips()
{
$empid = $this->session->userdata('EMPLOYEE_ID');
$orgid = $this->session->userdata('CURRENT_ORG_ID');
$where = "EMPLOYEE_ID ='".$empid."' ";
$response = array();
$queryString = "SELECT
em.EMPLOYEE_ID,
em.EMPLOYEE_NAME
FROM
uk_new_salary_slip assd,
employee_master em
WHERE
em.".$where."
GROUP BY em.EMPLOYEE_ID
order by em.EMPLOYEE_NAME asc";
$query = $this->db->query($queryString);
foreach ($query->result() as $data)
{
$result = array();
$result['EMPLOYEE_NAME'] = $data-> EMPLOYEE_NAME;
$queryString = "SELECT
mo.months,
MONTH((assd.pay_period)) as monthss,
YEAR((assd.pay_period)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(assd.id)) as action,
GROUP_CONCAT(DISTINCT(assd.ORG_ID)) as org
FROM
uk_new_salary_slip assd,
employee_master em,
months mo
WHERE
assd.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((assd.pay_period))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$queryString1 = "SELECT
mo.months,
MONTH((germany.pay_from)) as monthss,
YEAR((germany.pay_from)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(germany.id)) as action,
GROUP_CONCAT(DISTINCT(germany.ORG_ID)) as org
FROM
new_germany_salary_slip germany,
employee_master em,
months mo
WHERE
germany.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((germany.pay_from))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$queryString2 = "SELECT
mo.months,
MONTH((poland.pay_from)) as monthss,
YEAR((poland.pay_from)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(poland.id)) as action,
GROUP_CONCAT(DISTINCT(poland.ORG_ID)) as org
FROM
new_poland_salary_slip poland,
employee_master em,
months mo
WHERE
poland.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((poland.pay_from))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$query1 = $this->db->query($queryString);
$query2 = $this->db->query($queryString1);
$query3 = $this->db->query($queryString2);
$children = array();
foreach ($query1->result() as $data1)
{
$yearArray = array();
$yearArray['month'] = $data1->months;
$yearArray['year'] = $data1->PAY_YEAR;
$yearArray['org'] = $data1->org;
$yearArray['action'] = $data1->action;
array_push($children, $yearArray);
}
foreach ($query2->result() as $data2)
{
$yearArray = array();
$yearArray['month'] = $data2->months;
$yearArray['year'] = $data2->PAY_YEAR;
$yearArray['org'] = $data2->org;
$yearArray['action'] = $data2->action;
array_push($children, $yearArray);
}
foreach ($query3->result() as $data3)
{
$yearArray = array();
$yearArray['month'] = $data3->months;
$yearArray['year'] = $data3->PAY_YEAR;
$yearArray['org'] = $data3->org;
$yearArray['action'] = $data3->action;
array_push($children, $yearArray);
}
$result['children'] = $children;
array_push($response, $result);
}
return $response;
}
If in the month array the year is same then the IN action value should be 4,2 . If you see in object 0th and 4th month and year is the same so both object's action values should be in one row, and similarly its org value should be org:40,47 respectively.
{month:"FEBRUARY", year:"2018",org:"40,47",action:"4,2"}
I want the data to be formatted like this but in my case it shows different rows for each action.
Array push just adds elements on to the end of the array. It is not what you want. You want to essentially compound elements of the same year and month. To do that we can assign that as the 1st sub array key and simply append the array values to org and action:
$output = array();
foreach ($query1->result() as $data1) {
$key = $data1->PAY_YEAR . $data1->months;
if (!isset($output[$key]['month'])) {
$output[$key]['month'] = $data1->months;
$output[$key]['year'] = $data1->PAY_YEAR;
}
$output[$key]['org'][] = $data1->org;
$output[$key]['action'][] = $data1->action;
}
foreach ($query2->result() as $data2) {
$key = $data2->PAY_YEAR . $data2->months;
if (!isset($output[$key]['month'])) {
$output[$key]['month'] = $data2->months;
$output[$key]['year'] = $data2->PAY_YEAR;
}
$output[$key]['org'][] = $data2->org;
$output[$key]['action'][] = $data2->action;
}
foreach ($query3->result() as $data3) {
$key = $data3->PAY_YEAR . $data3->months;
if (!isset($output[$key]['month'])) {
$output[$key]['month'] = $data3->months;
$output[$key]['year'] = $data3->PAY_YEAR;
}
$output[$key]['org'][] = $data3->org;
$output[$key]['action'][] = $data3->action;
}
echo '<pre>';
print_r(array_keys($output));
I have the following PHP, that needs to take a list of article ids and run it through a function to get them all from the database.
I am very much a beginner in PHP so far I have:
list($slide1, $slide2, $slide3, $slide4, $slide5) = explode(" ", $params->get('id'));
$a = array(
$item => $slide1,
"two" => $slide2,
// "three" => $slide3,
// "four" => $slide4,
// "five" => $slide5
);
foreach ($a as $k) {
$args['id'] = $k;
$item = ModArticleSlider::getArticles($args);
}
and the class:
class ModArticleSlider {
public function getArticles($args){
$db = &JFactory::getDBO();
$item = "";
$id = $args['id'];
if($id > 0){
$query = "select * ";
$query .= "FROM #__content WHERE id =".$id." AND state=1 " ;
//echo $query;
$db->setQuery($query);
$item = $db->loadObject();
}
return $item;
}
}
How would i get it so that instead of specifying $item to have it almost dynamic so that i can get all the selected articles and place them in different variables.. or would i have to place them in a array?
Any Advice/Answers Greatly Appreciated.
Another approach, and possibly more performant as it would require only one database query (versus one for each article), would be to use http://docs.joomla.org/JDatabase::loadObjectList
So, you could instead pass an array of your articles ids as $ids to your class like:
public function getArticles($ids){
if ($ids) {
$db = JFactory::getDbo();
$query = "SELECT * FROM #__content WHERE id IN (" . implode(',', $id) . ") AND state=1 " ;
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
return FALSE;
}
$rows is returned as an array so you can then process it as needed.
i am also beginner of PHP.
Please Try this:
foreach ($a as $k => $val) {
$args = $val;
$item[] = ModArticleSlider::getArticles($args);
var_dump($item);
}
in your class
simply
$id = $args;
i hope it will help you!
Store the articles into an array, you can try this:
$slides = explode(" ", $params->get('id'));
$articleArray = array();
foreach($slides as $slide) {
$articleArray[] = ModArticleSlider::getArticles($slide);
}
var_dump($articleArray);
Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";
I have a wallposts MySql table with a tag_filter field, this field will have a comma seperated value.
I want to get all the unique/distinct tags for a user from this tag_filter field and populate in ul element.
There could be many posts per user.
eg
post1: tag_filter = a, b, c
post2: tag_filter = a, d, e
post3: tag_filter = c, d, e
the desired output would be
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
Here is my code thus far:
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$list = "<ul>";
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
foreach( $info as $item ) {
$list.="<li>$item</li>\n";
}
}
$list .= "</ul>";
echo $list;
I would also like to populate a js var with the distinct/unique list acquired from the above.
var sampleTags = [
<?php
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$all_tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
$all_tags = array_merge($all_tags, $info);
}
$tags = array_unique($all_tags); // values will be sorted by the function
foreach( $tags as $item ) {
$list = "$item";
}
echo join(',', $list);
?>
];
This might help.
$tag_filter_list = mysql_query('SELECT tag_filter from wallposts where userid = '.$USER->id);
$tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$tags[] = explode(",", $value); // put all in an array
}
// now, join and remove duplicates and sort in ascending order
$tags = implode( ',', $tags );
$tags = explode( ',', $tags );
$tags = array_values( array_unique( $tags ) );
sort($tags);
$list = "<ul>";
foreach( $tags as $item ) {
$list .= "<li>$item</li>\n";
}
$list .= "</ul>";
echo $list;
Hope this helps.
Comma separated values in a MySQL field is a sign of a bad database design, linked tables should be used if possible.
However, in your case, the following code might work:
$all_tags = array();
while ($tag_filter = mysql_fetch_array($tag_filter_list)) {
$value = $tag_filter["tag_filter"];
$info = explode(",", $value);
$all_tags = array_merge($all_tags, $info);
}
$tags = array_unique($all_tags); // values will be sorted by the function
foreach( $tags as $item ) {
$list .= "<li>$item</li>\n";
}
To put all tags in a javascript variable:
<script type="text/javascript">
var sampleTags = [<?php echo explode(', ', $tags); ?>];
</script>
Try merging all tag_filter arrays with array_merge() and then use array_unique() to remove duplicates.
Just try with the following example :
<?php
$post_array = array('a,b,c','a,d,e','c,d,e');
$tag_list = '<ul>';
$i=0;
while($i < count($post_array)){
$filter_explode = explode(',',$post_array[$i]);
$filter_count = count($filter_explode);
for($j=0;$j<$filter_count;$j++)
{
if(!in_array($filter_explode[$j],$tag_list_build)){
$tag_list_build[] = $filter_explode[$j];
}
}
$i++;
}
$tag_list_build_count = count($tag_list_build);
for($k=0;$k<$tag_list_build_count;$k++)
{
$tag_list.= '<li>'.$tag_list_build[$k].'</li>';
}
$tag_list.= '</ul>';
echo $tag_list;
?>
I think this may help you to resolve your problem.
this is continued from another question i asked:
Listing out JSON data?
my search only returns 1 item, im pretty sure the problem lies somewhere in my php, im not too sure if im adding to the array properly, or it could be the javascript wich you can see on the above link, but i doubt it.
my php code:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
$i = 0;
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[$i]['title'] = $node->title;
$matches[$i]['link'] = $termlink->tid;
}
++$i;
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
You appear to be incrementing your $i variable AFTER the foreach loop. Therefore, $i is always 0 throughout your loop, so you are always setting the title and link values for $matches[0].
Try this:
function mytheme_ajax_response() {
$search = $_GET["search_text"];
$result = db_query("SELECT nid FROM {node} WHERE title LIKE '%s%' AND type = 'product_collection'", $search);
$noder = array();
while ($record = db_fetch_object($result)) {
$noder[] = $record;
}
$matches = array();
foreach ($noder as $row) {
$node = node_load($row->nid);
$termlink = db_fetch_object(db_query("SELECT tid FROM {term_node} WHERE nid = %d", $row->nid));
$matches[] = array('title' => $node->title, 'link' => $termlink->tid);
}
$hits = array();
$hits['matches'] = $matches;
print json_encode($hits);
exit();
}
The $i wasn't incrementing the code as it was outside the foreach loop. By making a second array as above you don't need it anyway... (hope this works)...