explode function in codeigniter - php

I am new to programming , i have a problem while using explode function ie, after i explode the value and pass those value to a model to retrive records from db only the last value from the exploded data is showing.
ex i have impoded data as (test,test1,test2) after explode the data is like(testtest1test2) here i pass these value to model to take records from a table where a field name is equal to the exploded value.I dont't know how to explain this properly please forgive me.
public function location($id) {
$query = $this->gt_pav_model->select($id);
$data['selectdata'] = $query->result();
foreach( $data['selectdata'] as $s) {
$explode = $s->package_id; // this is to get imploded data from db
}
$t = explode(",", $explode);
foreach( $t as $tt) {
$query = $this->gt_pav_model->select_pa($tt);
$data['dataa'] = $query->result();
$this->load->view('pav/pavdetails',$data);
}
}

public function location($id) {
$final_result = array();
$result= $this->gt_pav_model->select($id)->result();
foreach( $result as $key=> $re) {
$explode = $re->package_id;
$t = explode(",", $explode);
$param = $t[1];
$datas = $this->gt_pav_model->select_pa($param)->result();
$final_result[$key] => $datas;
}
$this->load->view('pav/pavdetails',array('datas'=>$final_result));
}
You can print result in your view page <?php print_r($datas); ?>

Related

How to get data from database that result as an array in model codeigniter

I want to make a query that results like this in codeigniter MODEL:
$caldata = array (
15 => 'yes',
17 => 'no'
);
Is that possible to do?
Take NOTE: The 15,17 and yes,no are in the same database table.
There is no core helper function to achieve what you want in CI. But you can create your own helper function:
function pluck($arr = [], $val = '', $key = '')
{
// val - label for value in array
// key - label for key in array
$result = [];
foreach ($arr as $value) {
if(!empty($key)){
$result[$value[$key]] = $value[$val];
}else{
$result[] = $value[$val];
}
}
return $result;
}
you can use result_array() function so you can have something like:
$query = $this->db->select('id,answer')->from('users')->get();
$result = $query->result_array();
print_r($result);
After that you have your array and you can make the $key => $value relation of the fields
After a long search i found an answer. Sample way to do this:
$query = $this->db->select('start_date, class')->from('event')->like('start_date', "$year-$month", 'after')->get();
$datavariable = $query->result();
$caldata = array();
foreach($datavariable as $row){
$caldata[substr($row->start_date,8,2)] = $row->class;
}

How to compare associative array with result_array in 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.

Pulling NHL Standings from XML Table with PHP

I'm working on a project in which I pull various statistics about the NHL and inserting them into an SQL table. Presently, I'm working on the scraping phase, and have found an XML parser that I've implemented, but I cannot for the life of me figure out how to pull information from it. The table can be found here -> http://www.tsn.ca/datafiles/XML/NHL/standings.xml.
The parser supposedly generates a multi-dimmensional array, and I'm simply trying to pull all the stats from the "info-teams" section, but I have no idea how to pull that information from the array. How would I go about pulling the number of wins Montreal has? (Solely as an example for the rest of the stats)
This is what the page currently looks like -> http://mattegener.me/school/standings.php
here's the code:
<?php
$strYourXML = "http://www.tsn.ca/datafiles/XML/NHL/standings.xml";
$fh = fopen($strYourXML, 'r');
$dummy = fgets($fh);
$contents = '';
while ($line = fgets($fh)) $contents.=$line;
fclose($fh);
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
print_r($arrOutput[0]); //This print outs the array.
class xml2Array {
var $arrOutput = array();
var $resParser;
var $strXmlData;
function parse($strInputXML) {
$this->resParser = xml_parser_create ();
xml_set_object($this->resParser,$this);
xml_set_element_handler($this->resParser, "tagOpen", "tagClosed");
xml_set_character_data_handler($this->resParser, "tagData");
$this->strXmlData = xml_parse($this->resParser,$strInputXML );
if(!$this->strXmlData) {
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($this->resParser)),
xml_get_current_line_number($this->resParser)));
}
xml_parser_free($this->resParser);
return $this->arrOutput;
}
function tagOpen($parser, $name, $attrs) {
$tag=array("name"=>$name,"attrs"=>$attrs);
array_push($this->arrOutput,$tag);
}
function tagData($parser, $tagData) {
if(trim($tagData)) {
if(isset($this->arrOutput[count($this->arrOutput)-1]['tagData'])) {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] .= $tagData;
}
else {
$this->arrOutput[count($this->arrOutput)-1]['tagData'] = $tagData;
}
}
}
function tagClosed($parser, $name) {
$this->arrOutput[count($this->arrOutput)-2]['children'][] = $this->arrOutput[count($this- >arrOutput)-1];
array_pop($this->arrOutput);
}
}
?>
add this search function to your class and play with this code
$objXML = new xml2Array();
$arrOutput = $objXML->parse($contents);
// first param is always 0
// second is 'children' unless you need info like last updated date
// third is which statistics category you want for example
// 6 => the array you want that has wins and losses
print_r($arrOutput[0]['children'][6]);
//using the search function if key NAME is Montreal in the whole array
//result will be montreals array
$search_result = $objXML->search($arrOutput, 'NAME', 'Montreal');
//first param is always 0
//second is key name
echo $search_result[0]['WINS'];
function search($array, $key, $value)
{
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $subarray)
$results = array_merge($results, $this->search($subarray, $key, $value));
}
return $results;
}
Beware
this search function is case sensitive it needs modifications like match to
a percentage the key or value changing capital M in montreal to lowercase will be empty
Here is the code I sent you working in action. Pulling the data from the same link you are using also
http://sjsharktank.com/standings.php
I have actually used the same exact XML file for my own school project. I used DOM Document. The foreach loop would get the value of each attribute of team-standing and store the values. The code will clear the contents of the table standings and then re-insert the data. I guess you could do an update statement, but this assumes you never did any data entry into the table.
try {
$db = new PDO('sqlite:../../SharksDB/SharksDB');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo "Error: Could not connect to database. Please try again later.";
exit;
}
$query = "DELETE FROM standings";
$result = $db->query($query);
$xmlDoc = new DOMDocument();
$xmlDoc->load('http://www.tsn.ca/datafiles/XML/NHL/standings.xml');
$searchNode = $xmlDoc->getElementsByTagName( "team-standing" );
foreach ($searchNode as $searchNode) {
$teamID = $searchNode->getAttribute('id');
$name = $searchNode->getAttribute('name');
$wins = $searchNode->getAttribute('wins');
$losses = $searchNode->getAttribute('losses');
$ot = $searchNode->getAttribute('overtime');
$points = $searchNode->getAttribute('points');
$goalsFor = $searchNode->getAttribute('goalsFor');
$goalsAgainst = $searchNode->getAttribute('goalsAgainst');
$confID = $searchNode->getAttribute('conf-id');
$divID = $searchNode->getAttribute('division-id');
$query = "INSERT INTO standings ('teamid','confid','divid','name','wins','losses','otl','pts','gf','ga')
VALUES ('$teamID','$confID','$divID','$name','$wins','$losses','$ot','$points','$goalsFor','$goalsAgainst')";
$result= $db->query($query);
}

codeigniter controller input Hebrew letters

I have a function in the controller that gets a string and then queries the database (via the model) for records that have this string as their name. This works fine with English but I have a problem when the input is in Hebrew. When I echo the string I see something like %D7%91 and the query fails.
All database tables entries are defined as utf8_general_ci.
My controller code:
function get_records_by_name($name)
{
echo 'searching for: '.$name.'</br>';
$keys = new DMkeys() ;
$query = $keys->get_keys();
$arr = array();
$count = 0;
foreach ($query->result() as $row)
{
if(stristr($row->name, $name) != FALSE)
{
$arr[] = $row->name;
$count++;
echo $row->name.'</br>';
}
}
$result = array('count' => $count, 'list' => $arr);
echo json_encode($result) ;
}
My model code:
function get_keys()
{
$query = $this->db->get('keys');
return $query;
}
Thanks,
Simon
You need to decode the variable before using it, try:
$name = urldecode($name);

PHP array group by data values

This is my $data variable:
cv = 1,2,3,4,5:::cpt = 4,5 ...
Now I need some function, where I can add the number as param (number will be $data number value).
for example.
function getPermission($id) {
... return $something;
}
Then if I call the function like: echo getPermission(4); it'll print out the data 'keys' where the 4 will be inside, as a value.
So, to be clear:
if I call the function like this:
echo getPermission(4); output will be "cv" and "cpt".
but if I call it this way:
echo getPermission(1);
it'll only output "cv" because number (1) is located in the cv key.
Hope you guys understand, feel free to ask if something aren't clear enough.
$str = 'cv = 1,2,3,4,5:::cpt = 4,5';
$tmp = explode(':::', $str);
$data = array();
foreach ($tmp as $arr) {
$tokens = explode(' = ', $arr);
$data[$tokens[0]] = explode(',', $tokens[1]);
}
print_r(getPermission(4, $data));
print_r(getPermission(1, $data));
function getPermission($id, $data) {
$out = array();
foreach ($data as $key => $arr) {
if (in_array($id, $arr)) $out[] = $key;
}
return $out;
}

Categories