I use Zend 1
CONTROLLER:
public function insertarAction() {
$entidades_salud = new Application_Model_DbTable_EntidadesSalud();
$datos_entidades = $entidades_salud->buscarEntidades();
}
MODEL:
<?php
class Application_Model_DbTable_EntidadesSalud extends Zend_Db_Table_Abstract
{
protected $_name = 'entidades_salud';
protected $_primary = 'codigo_entidad_salud';
public function buscarEntidades() {
$consulta = $this->select()->from($this->_name);
$query = $this->fetchAll($consulta)->toArray();
return $query;
}
}
PRINT OF CONSULT [print_r($datos_entidades); - in controller]
Array ( [0] => Array ( [codigo_entidad_salud] => 1 [nombre_entidad] => SANITAS )
[1] => Array ( [codigo_entidad_salud] => 3 [nombre_entidad] => wladfimir )
[2] => Array ( [codigo_entidad_salud] => 4 [nombre_entidad] => Juli ))
no entraArray ( [controller] => beneficiarios [action] => insertar [module] => default )
According to the above result, I require print:
1 SANITAS
3 wladfimir
4 Juli
I think it should work with something like:
while($row = mysqli_fetch_assoc($datos_entidades)){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
What you need is foreach loop to iterate through an array.
foreach($datos_entidades as $row){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
Note: The display logic should fall into the view file, you should pass data to view & in view file you need loop to display the records.
You are converting The results into array,
you can do what Rikesh Suggested as,
foreach($datos_entidades as $row){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
And you can pass $datos_entidades to View Script
as $this->view->data= $datos_entidades;
and you will be able to use,
foreach($this->data as $row){
echo $row['codigo_entidad_salud'];
echo $row['nombre_entidad'];
}
in your view script also,
an alternate approach,
You dont use toArray() in $query = $this->fetchAll($consulta)->toArray();
just use, $query = $this->fetchAll($consulta);
and you will be able access it like following,
foreach($datos_entidades as $row){
echo $row->codigo_entidad_salud;
echo $row->nombre_entidad;
}
and will be able to access same way in view script also.
Related
I have an employees table and some of the employees are managers.
I need a function that takes an employee ID and creates a multi-dim array with all the employees that report to them. So far I was able to print the tree:
function drillDownStaff($emplid){
$conn = db_connect();
$sql = "SELECT
employees.EmployeeID, employees.ManagerID
FROM
employees
WHERE
employees.ManagerID = '".$emplid."';
$result = mysql_query($sql,$conn);
while($row = mysql_fetch_assoc($result)){
echo "<ul>";
echo "<li>".$row['FullName'];
drillDownStaff($row['EmployeeID']);
echo "</li>";
echo "</ul>";
}
}
This will print out a nice manager->employee tree:
John
Jane
Paul
Maria
Mark
Tony
Blane
Colleen
Roxy
Foxy
Lilly
Maureen
But what I'd like is the recursive function to return a multi-dim array with the employee tree like so:
array(
[5] => array(
[FullName] => John
[...] => Other emp details
[manages] => array(
[6]=>array(
[FullName]=>Jane
[...]=>other emp details
[manages]=> array(Pauls' details)
)
[7]=>array(...) // emp details again
)
)
)
Is this possible?
A recursive function to build the staff tree is as follows. Bear in mind this isn't very efficient, so don't expect it to be particularly performant if you have a tree of hundreds/thousands of staff members.
function buildStaffTree($managerId = null) {
global $staff;
$subordinates = array_values(array_filter(
$staff,
function ($staffMember) use ($managerId) {
return $staffMember['manager'] === $managerId;
}
));
if ($managerId === null) {
// Tree root - only enumerate the top-level managers
return array_map(
function ($subordinate) {
return buildStaffTree($subordinate['id']);
},
$subordinates
);
} else {
$manager = array_values(array_filter(
$staff,
function ($staffMember) use ($managerId) {
return $staffMember['id'] === $managerId;
}
))[0];
return [
'id' => $manager['id'],
'name' => $manager['name'],
'manages' => array_map(
function ($subordinate) {
return buildStaffTree($subordinate['id']);
},
$subordinates
)
];
}
}
An example of this code running is available here.
I have no idea why my query is suddenly not working (although maybe it was never working to begin with). Is there anything wrong here?
My controller;
$dataset = $postcode_lookup->dataset; // will return "201502_postcode"
$postcode_extract = new PostcodeExtract;
$postcode_extract = $postcode_extract->setTableByDate($dataset);
foreach ($input as $column => $values) {
$postcode_extract->orWhere(function ($query) use ($column, $values) {
$query->whereIn($column, $values);
});
}
/*
* Temporarily print out the raw SQL...
*/
$sql = str_replace(['%', '?'], ['%%', "'%s'"], $postcode_extract->toSql());
$fullSql = vsprintf($sql, $postcode_extract->getBindings());
print_r($fullSql);
exit;
My model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PostcodeExtract extends Model {
protected $connection = 'postcodes';
public function setTableByDate($selected_tablename)
{
$this->table = $selected_tablename;
// Return $this for method chaining
return $this;
}
public function getTable()
{
if (isset($this->table))
$this->setTableByDate($this->table);
return $this->table;
}
All that the print out of the raw sql is returning is select * from 201502_postcode and is just ignoring the rest of the query.
This is my $input array;
Array
(
[country] => Array
(
[0] => L93000001
[1] => M83000003
)
[county] => Array
(
[0] => 95
)
)
orWhere and whereIn is just being ignored it seems..
--- UPDATE ---
I didn't know about orWhereIn. But having tried this;
foreach ($input as $column => $values) {
$postcode_extract->orWhereIn($column, $values);
print "<br>";
print $column;
print "<br>";
print_r($values);
print "<br>";
}
I still get the same result. It's like this loop is being totally ignored - even though I can get these print's/print_r's to work. The raw SQL is still just select * from 201502_postcode.
Try this
$postcode_extract->orWhereIn($column, $values)
Also, if that doesnt work, try making the first one condition a whereIn and the rest a orWhereIn
Oh this is so frustratingly obvious I think I might cry...
foreach ($input as $column => $values) {
$postcode_extract = $postcode_extract->orWhereIn($column, $values);
}
I'm new in the object oriented programming so this question might be silly...
I've created my class in a separate file called classProduct.php
<?php
class product{
public $prodId;
public $prodName;
public $prodPrice;
public function __construct($prodId,$prodName,$prodPrice){
$this->prodId = $prodId;
$this->prodName=$prodName;
$this->prodPrice=$prodPrice;
}
public function get_prodId(){
return $this->prodId;
}
public function get_prodName(){
return $this->prodName;
}
public function get_prodPrice(){
return $this->prodPrice;
}
}
?>
Then I tried to create a new object in a $_SESSION variable. This happens in another file called dailySales.php where I include the previous file using:
include_once("classProduct.php");
What I want to do is to save in $_SESSION['myItems'] each new object. I am trying something like:
$newItem= new product($var,$var,$var);
$_SESSION['myItems']=array($newItem); // I believe here is where I do it wrong
Every time the buyer chooses one more products, the pages reloads (with ajax). When I echo or var_dump the $_SESSION['myItems'] I only get the last object. What do I need to change to get it working correctly?
Of course I do need the object so I can easily remove a product from the shopping cart if
'Delete' is pressed.
This is working for me locally.
Define your items session variable as an array, then push them into the variable using array_push
class product {
public $prodId;
public $prodName;
public $prodPrice;
public function __construct($prodId, $prodName, $prodPrice) {
$this->prodId = $prodId;
$this->prodName = $prodName;
$this->prodPrice = $prodPrice;
}
public function get_prodId() {
return $this->prodId;
}
public function get_prodName() {
return $this->prodName;
}
public function get_prodPrice() {
return $this->prodPrice;
}
}
Then use it like so:
$product = new product(1, "test", 23);
$product2 = new product(2, "test2", 43);
$_SESSION['items'] = array();
array_push($_SESSION['items'], $product, $product2);
echo '<pre>';
print_r($_SESSION['items']);
echo '</pre>';
This is the output of print_r()
Array
(
[0] => product Object
(
[prodId] => 1
[prodName] => test
[prodPrice] => 23
)
[1] => product Object
(
[prodId] => 2
[prodName] => test2
[prodPrice] => 43
)
)
I need to access multiple arrays, the problem lies when I get to the arrays I need like below, I can't access it traditionally because the key will be different every time.
I'm dealing with the following array:
Array
(
[oe_schedule_charge] => Array
(
[617cdb2797153d6fbb03536d429a525b] => Array
(
[schedule] =>
[args] => Array
(
[0] => Array
(
[id] => cus_2OPctP95LW8smv
[amount] => 12
)
)
)
)
)
There are going to be hundreds of these arrays and I need a way to efficiently access the data within them. I'm using the following code with expected output:
function printValuesByKey($array, $key) {
if (!is_array($array)) return;
if (isset($array[$key]))
echo $key .': '. $array[$key] .'<br>';
else
foreach ($array as $v)
printValuesByKey($v, $key);
}
$cron = _get_cron_array();
foreach( $cron as $time => $hook ) {
if (array_key_exists('oe_schedule_charge', $hook)) {
echo '<div>';
echo date('D F d Y', $time);
echo printValuesByKey($hook, 'amount');
echo printValuesByKey($hook, 'id');
echo '</div>';
}
}
But I've never had to deal with this much data, so I would like to take the proper precautions. Any light that can be shed on accessing a multidimensional array like this in an efficient way would be greatly appreciated.
I would consider loading it into an object, then writing member functions to get what you want.
class myclass {
private $_uniqueKey;
private $_schedule;
private $_args = array();
private $_amount = array();
private $_id = array();
public function __construct($arrayThing)
{
foreach($arrayThing['oe_schedule_charge'] as $uniqueKey => $dataArray)
{
$this->_uniqueKey = $uniqueKey;
$this->_schedule = $dataArray['schedule'];
$this->_args = $dataArray['args'];
}
$this->_afterConstruct();
}
private function _afterConstruct()
{
foreach($this->_args as $argItem)
{
if(isset($argItem['amount']) && isset($argItem['id']))
{
$this->_amount[] = $argItem['amount'];
$this->_id[] = $argItem['id'];
}
}
}
public function getUniqueKey()
{
return $this->_uniqueKey;
}
public function getSchedule()
{
return $this->_schedule;
}
public function getArgs()
{
return $this->_args;
}
public function printShitOut($time)
{
//You define this. But if you do a print_r( on the object, it will tell you all the items you need. )
}
//code would be like this:
$cron = _get_cron_array();
foreach( $cron as $time => $hook )
{
$obj = new myclass($hook);
$obj->printShitOut($time);
}
Using the following:
$last_book = tz_books::getLast($request->db, "WHERE book_id='{$request->book_id}'");
I get the following php object array,
[0] => tz_books Object
(
[db:tz_books:private] => com Object
[id] => 64BEC207-CA35-4BD2
[author_id] => 4F4755B4-0CE8-4251
[book_id] => 8FC22AA0-4A60-4BFC
[date_due] => variant Object
)
I then want to use the author_id, but for some reason it's not working.
Trying to use:
$tz_books->author_id;
Using print_r($last_book); prints the array to the console just fine. And Doing the following just to see if the correct variable was being used:
$author = $tz_books->author_id;
print_r($author);
Nothing is printed to the console, and even after digging through the php manual and trying a lot of alternatives, I can't seem to grab that variable. I'm hoping i'm making a rookie mistake and overlooking something stupid. Thank you for any help!
Edit: Class definition
private $db;
public $id;
public $author_id;
public $book_id;
public $date_due;
public function __construct($db, $values=null) {
$this->db = $db;
if ( $values != null ) {
foreach ( $values as $var => $value ) {
$this->$var = $value;
}
}
}
public static function retrieveAll($db, $where='', $order_by='') {
$result_list = array();
$query = 'SELECT '.
'id, '.
'author_id, '.
'book_id, '.
'date_due '.
"FROM tz_books $where $order_by";
$rs = $db->Execute($query);
while ( !$rs->EOF ) {
$result_list[] = new tz_books($db, array(
'id' => clean_id($rs->Fields['id']->Value),
'author_id' => clean_id($rs->Fields['author_id']->Value),
'book_id' => clean_id($rs->Fields['book_id']->Value),
'date_due' => $rs->Fields['date_due']->Value,
));
$rs->MoveNext();
}
$rs->Close();
return $result_list;
}
Your result object seems to be an array of books with 1 element.
Try
echo $tz_books[0]->author_id;
BTW, it also looks like you're escaping input by putting single quotes. This is not a reliable/recommended method. Use a database-specific escape function like this