How to compare associative array with result_array in PHP - php

Need to bind Page drop-down conditionally on base of 'Content' table. Page titles are stored in an associative array and 'Content' table have page code stored in it. Here is the code
Function which return page titles
public function getPageTitles(){
$pageTitles = array("Home"=> "Home",
"AboutUs"=> "About Us", //AboutUs will save in database as pageCode
"Features"=> "Features",
"ContactUs"=> "Contact Us");
return $pageTitles;
}
Function which checks if page have content or not:
public function getPageTitlesWithNoContent()
{
$pageTitles = $this->getPageTitles();
$this->db->distinct('pageCode');
$this->db->select('pageCode');
$this->db->from('content');
$this->db->where('status', 1);
$data = $this->db->get();
$queryResult = $data ? $data->result_array() : 0 ;
$emptyPageTitle = array();
foreach($pageTitles as $x => $x_value)
{
$hasContent = in_array($x, $queryResult);
if (!$hasContent){
$emptyPageTitle[$x] = $x_value;
}
}
return $emptyPageTitle;
}
This function is returning all page titles.. new to php no idea what is wrong

Check name fields in table is same? With Uppercase first char?
Also change your code in this loop:
foreach($pageTitles as $x => $x_value)
{
if (in_array($x, $queryResult)){
$emptyPageTitle[$x] = $x_value;
}
}
I remove ! negative in check condition

#NMathur I think you almost got it. Made some changes for you in that code, Check it.
public function getPageTitlesWithNoContent() {
$pageTitles = $this->getPageTitles();
$this->db->select('pageCode');
$this->db->from('content');
$this->db->where('status', 1);
$this->db->group_by('pageCode');
$query = $this->db->get();
$queryResult = array();
foreach ($query->result_array() as $row) { // This loop should need to form an array based on query result
$queryResult[$row['pageCode']] = $row['pageCode'];
}
$emptyPageTitle = array_diff_key($pageTitles,$queryResult); // Compares the keys from array1 against the keys from array2 and returns the difference
return $emptyPageTitle;
}

As #TamilvananN guided, I printed the queryResult and tried this workaround:
foreach($pageTitles as $x => $x_value)
{
foreach ($queryResult as $item)
{
if (!($x == $item['pageCode'])){
$emptyPageTitle[$x] = $x_value;
}
}
}
It is working, but as you can see this has loop in a loop .. that can be very costly .. can you please share any fast way to compare the results.

Related

Facing some problem but can't solved this

When i using this below without where condition query i get the values
Model:
public function get_teacher_number() {
$this->db->select('staff.*');
$this->db->from('staff');
$this->db->join('staff_roles','staff.id=staff_roles.staff_id','inner');
$query = $this->db->get();
return $query->result_array();
}
Output:
2323232,262626,32323,,26262623265265,
When i using this below with where condition query i can't get all the values it show me just one value but when i tried this sql in my mysql server its show me 2 values and here i get only one value.
Model:
public function get_teacher_number() {
$this->db->select('staff.*');
$this->db->from('staff');
$this->db->join('staff_roles','staff.id=staff_roles.staff_id','inner');
$this->db->where('staff_roles.role_id',2);
$query = $this->db->get();
return $query->result_array();
}
Output:
262626,,
one value is missing..
Here i give you controller code:
$all_teacher = $this->teacher_model->get_teacher_number();
$x = '';
foreach ($all_teacher as $val) {
$smsid= $val["id"];
$number = $val["contact_no"];
$x = $x.$number.","; //number separated by comma
}
echo "<pre>";
print_r($x);
exit();

moved working routine to function, now results are not present

As I try to consolidate my code and make it more available to other projects, I've run into a problem:
variables that were generated and available are not anymore when that routine is moved to a function:
This is the query:
$count = "SELECT eid, Count, Name, name2, Email, pay FROM h2018";
THIS WORKS FINE:
$result = $mysqli->query($count);
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
echo($a." and ".$value."<BR>");
}
NOT WORKING FINE:
function avar($result) {
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
}
}
$result = $mysqli->query($count);
avar($result);
echo($a." and ".$value."<BR>");
I thought the variable variables would be available from outside of the function. I tried doing a return, but that didn't help. I also tried to global $$key, but that didn't work either.
What am I doing wrong?
There is multiple mistakes or missing steps like return or array
function avar($result) {
$data=array();
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$data[$key] = $value;//if there is multiple records then used array otherwise you should used variable
}
return $data;
}
$result = $mysqli->query($count);
$data=avar($result);//get return value
print_r($data);
Please, read the PHP documentation about the Variable Scope for more information. The variables inside your function are local so you cannot access them outside of your function. You would have to return something.
For example, this could work:
function avar($result) {
$resultArray = false;
$row = $result->fetch_assoc();
foreach ($row as $key => $value) {
$resultArray = [
'key' => $key,
'value' => $value
];
}
return $resultArray;
}
$result = $mysqli->query($count);
$queryResult = avar($result);
if ($queryResult) {
echo 'Key: ' . $queryResult['key'] . ' | Value: ' . $queryResult['value'];
}
Please do note that fetch_assoc will return an array with multiple items if there is more than one result. In my example only one (and the last) result will be returned.
Edit: As #Nigel Ren said in his comment. In this case you're basically rebuilding an array which is going to look (nearly) the same as the array which is being returned by fetch_assoc, which is pointless. My function can be used if you want to add conditions in the future, or manipulate some data. Otherwise, don't use a function and just use the results from fetch_assoc.

set href link for each row in codeigniter table

Let's think that we have a db and a model function that retrieve a query result like this:
public function lista_ordini ($idcliente)
{
$this->db->select('ordini.num_fattura, misure.cosplay, ordini.data_richiesta,
ordini.anticipo, ordini.data_consegna,
ordini.saldo_totale, ordini.stato');
$this->db->join('misure', "ordini.id_cliente = $idcliente");
$query = $this->db->get('ordini');
if ($query && $query->num_rows() > 0){
return $query;
}else{
echo "errore generazione query ordini";
}
}
}//This is missing in your original, I'm not sure if it's a typo
Using codeigniter's table helper to generate a table:
<?php echo $this->table->generate($query); ?>
I can generate the table...and this is ok and works...
but, What if I want that every rows has a specific field (or the entire row if it's simpler) with href link? (this link will pass thorough GET method a variable for generate another query, but I don't figure out yet how that will work, this is just an hobby project)
I try this:
public function lista_ordini ($idcliente)
{
$this->db->select('ordini.num_fattura, misure.cosplay, ordini.data_richiesta,
ordini.anticipo, ordini.data_consegna, ordini.saldo_totale,
ordini.stato');
$this->db->join('misure', "ordini.id_cliente = $idcliente");
$query = $this->db->get('ordini');
if ($query && $query->num_rows() > 0) {
$rows = $query->row();
foreach ($rows as &$row) {
$row['num_fattura'] = ''.$row['num_fattura'].'';
}
return $rows;
}else{
echo "errore generazione query ordini";
}
}
I'm pretty sure that foreach loop is the way, but I can't understand how, cause I have so much errors that I cannot understand...to make this simply, my code doesn't work, and I think that I need some semantic advice.
thank you in advace
There is a logical problem in the foreach loop here:
foreach ($rows as &$row) {
$row['num_fattura'] = ''.$row['num_fattura'].'';
}
return $rows;
Each time the loop runs you are changing the value of $row, but when it completes you are returning $rows, which is unchanged.
Instead, you could edit the original array, using $k => $v to access the key and value inside the foreach loop:
foreach ($rows as $k => $v) {
$rows[$k]['num_fattura'] = ''.$rows[$k]['num_fattura'].'';
}
return $rows;
I know what you're trying to do, but I dont understand how you are trying to do it. Here's How I would do it:
//controller method
public function show_data()
{
$this->load->library('table');
$data['table_data'] = $this->some_model->get_the_data();
$this->load->view('some_view_that_will_contain_my_table', $data);
}
Now in my view, I'd generate the table:
<!doctype html>
...
<?if(!empty($table_data)):?>
<? $this->table->set_heading('column_1', 'column_2');?>
<?foreach($able_data as $table_row):
$this->table->add_row(
array('data'=>''.$table_row['column_1'].'.'),
array('data'=>''.$table_row['column_2'].'.'),
);
endforeach;?>
<?= $this->table->generate();?>
<?endif;?> //or display an empty table

building an associative array

This is going to be my first time building an associative array. And if anyone can help me I would be grateful.
Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.
So here's what I have got so far:
function getTitleandID($editorName) {
$listofTitlesandIDs = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
if ($editorName == $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()"))
{
$title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id[1]");
$listofTitlesandIDs[] = //I don't know what to do here
}
else
{
$listofTitlesandIDs = null;
}
}
return $listofTitlesandIDs
}
This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]
So that's about it. I'm grateful for any help you have time to provide.
Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.
function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id");
$editorName = $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()")
if ($editorName[0] == "$EditorName")
{
$result = array("title"=>$title[0], "id"=>$id[0]);
$list[] = $result;
}
}
return $list;
}
With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:
foreach ($list as $instance)
{
echo $instance['title'];
echo $instance['id'];
}
Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.
$listofTitlesandIDs[$id] = $title;
You should loop over the array then using the foreach loop.

How can I convert db query result to array

original I thought the $query is array object, since I can print these data to a list table like this.
my controller code
$data['dates'] = $this->calendar_model->get_cal_eventDate();
$this->load->library('table');
$this->load->view('my_test', $data);
my view code
echo $this->table->generate($dates);
but when I changed my code to try to print $tbDataArr via foreach. It didn't work. How can I convert the $query result (eventDate field values) to array object.
function get_cal_eventDate() {
$this->db->select('eventDate');
$query = $this->db->get('tb_event_calendar');
return $query;
}
$tbDataArr = $this->calendar_model->get_cal_eventDate();
foreach ($tbDataArr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
Are you using CodeIgniter? If you are you can do this
function get_cal_eventDate() {
$this->db->select('eventDate');
$query = $this->db->get('tb_event_calendar');
$result = $query->result_array();
return $result;
}
If not need more info about what your doing with your PHP.
Codeigniter, right?
Use the $query->result_array() method.
see more here:
http://codeigniter.com/user_guide/database/results.html
//Convert $query->result_array() to $query->result() after add new field in array
$result = $query->result_array();
for($i=0;$i<$query->num_rows();$i++){
//insert new field in array (test_field with value 1)
$result[$i]+=array('test_field'=>1);
$result[$i] = (object)$result[$i];
}
return $result; //equivalent to return $query->result() without new field;

Categories