<?php
/* SC: Shop Category */
$SCStatement = "SELECT * FROM shop_categories";
$SCQuery = mysql_query($SCStatement);
while($SCFetch = mysql_fetch_array($SCQuery)){
$SCItems[] = array(
'id' => $SCFetch['id'],
'name' => $SCFetch['cat_name'],
'desc' => $SCFetch['cat_description']
);
}
$SCNumCols = 2;
$SCNumItems = count($SCItems);
$SCNumRows = ceil($SCNumItems / $SCNumCols);
function bindArrayToObject($array) {
$return = new stdClass();
foreach ($array as $k => $v) {
if (is_array($v)) {
$return->$k = bindArrayToObject($v);
}
else {
$return->$k = preg_replace ('/<[^>]*>/', '', $v);
}
}
return $return;
}
$newObject = bindArrayToObject($SCItems);
echo $newObject->name;
?>
The data i retrieve from the database is stored in $SCItems[] array. The problem is, when i echo the $newObject->name; nothing will appear. What to add this code to show the data using $newObject->name;
Thanks in advance.
Well, judging from this code, what you have is something like
$SCItems = Array(
0 => Array(
'id' => 1,
'name' => 'name 1',
'desc' => 'description 1'
),
1 => Array(
'id' => 2,
'name' => 'name 2',
'desc' => 'description 2'
),
);
And then from that your bindArrayToObject function trying to build the object
$newObject = new stdClass();
$newbject->0 = new stdClass();
$newbject->0->id = 1;
$newbject->0->name = 'name 1';
$newbject->0->desc = 'description 1';
$newbject->1 = new stdClass();
$newbject->1->id = 2;
$newbject->1->name = 'name 2';
$newbject->1->desc = 'description 2';
So, what you probably should do is loop over your '$SCItems' and then on each entry use bindArrayToObject
Such as
$SCObject = Array();
foreach($SCItems as $SCItem) {
$SCObjects[] = bindArrayToObject($SCItem);
}
From there you should be able to access $SCObjects[0]->name, which would make much more sense to me
Related
So, I have a switch statement inside a foreach loop that checks the value of a field in the array and uses the value to build a named array and email address variable for each unique value. Question is below example code.
As an example, if the values are foo, bar, and foobar, then the following occurs:
switch($value['value']) {
case 'foo':
if(!isset($foo)){
$foo = array();
}
if(!isset($email_foo)){
$email_foo = convert_to_email($value['value']);
}
array_push($foo, $value);
break;
case 'bar':
if(!isset($bar)){
$bar = array();
}
if(!isset($email_bar)){
$email_bar = convert_to_email($value['value']);
}
array_push($bar, $value);
break;
case 'foobar':
if(!isset($foobar)){
$foobar = array();
}
if(!isset($email_foobar)){
$email_foobar = convert_to_email($value['value']);
}
array_push($foobar, $value);
break;
default:
if(!isset($default)){
$default = array();
}
if(!isset($email_default)){
$email_default = 'this#isemail.com';
}
array_push($default, $value);
}
Resulting in 4 different email addresses:
$email_foo = 'foo#isemail.com';
$email_bar = 'bar#isemail.com';
$email_foobar = 'foobar#isemail.com';
$email_default = 'default#isemail.com';
and 4 different arrays of data:
$foo = array(
0 => array(
'value' => 'F Oo',
'name' => 'Janet',
'age' => 23
),
1 => array(
'value' => 'F Oo',
'name' => 'Doug',
'age' => 42
)
)
$bar = array(
0 => array(
'value' => 'B Ar',
'name' => 'James',
'age' => 23
),
1 => array(
'value' => 'B Ar',
'name' => 'Donald',
'age' => 42
)
)
etc...
So, here is the question:
Is it possible to write a class that can be used to create all of the named arrays and email variables? Sort of something like this:
class Account_Manager_Build
{
public function __construct()
{
if(!isset($this)){
$this = array();
}
if(!isset("email_$this")){
"email_$this" = convert_to_email($this->value['value']);
}
array_push($this, $this->value);
}
}
For testing purposes, here is the function convert_to_email that is used throughout the examples:
function convert_to_email($input){
$returned = strtolower(substr($input, 0, 1)).strtolower(end(str_word_count($input, 2))).'#ismail.com';
return $returned;
}
Actually, you can create dynamically variables using the $$ notation:
$variable = "email_$name";
$$variable = "something";
However I'm not sure of what you're trying to do
What's the point of computing $email_something if it can be easily computed from something?
Why do you create those variables instead of just storing this in an array?
My code just populates the last array in the array $workshops
my loop function populates array $workshops, like so
while (ECSE_purchase::have_products()) {
ECSE_purchase::the_product();
$prodid = ECSE_purchase_product::get_the_ID();
$workshop_data = ETICKETDATA::get_workshop_details_helper($prodid);
$workshops = array();
if($prodid == 565) {
............
} else {
$workshopsTmp = array();
$workshopsTmp['workshop_barcode'] = $data['workshop_barcode'];
$workshopsTmp['workshop_id'] = ECSE_purchase_product::get_the_ID();
$workshopsTmp['workshop_title'] = ECSE_purchase_product::get_the_name();
$workshopsTmp['workshop_time'] = $workshop_data['time'];
$workshopsTmp['workshop_room'] = $workshop_data['room'];
$workshopsTmp['workshop_num_of_tickets'] = ECSE_purchase_product::get_the_QTY();
$workshops[] = $workshopsTmp;
}
But here i just get the last array and not like this:
$workshops = array(array('workshop_barcode' => '0101010101',
'workshop_id' => '589',
'workshop_title' => 'Swimming',
'workshop_time' => '12:00',
'workshop_room' => 'Room 1',
'workshop_num_of_tickets' => '2'),
array('workshop_barcode' => '03030303003',
'workshop_id' => '568',
'workshop_title' => 'Running',
'workshop_time' => '15:00',
'workshop_room' => 'Room 3',
'workshop_num_of_tickets' => '3'),
array('workshop_barcode' => '0505050505',
'workshop_id' => '570',
'workshop_title' => 'Biking',
'workshop_time' => '16:00',
'workshop_room' => 'Room 2',
'workshop_num_of_tickets' => '2'));
Any pointers appreciated.
regards,
just edit the loop
You keep redefining your initial array. Try putting $workshops array before while loop
$workshops = array();
while (ECSE_purchase::have_products()) {
ECSE_purchase::the_product();
$prodid = ECSE_purchase_product::get_the_ID();
$workshop_data = ETICKETDATA::get_workshop_details_helper($prodid);
if($prodid == 565) {
............
} else {
$workshopsTmp = array();
$workshopsTmp['workshop_barcode'] = $data['workshop_barcode'];
$workshopsTmp['workshop_id'] = ECSE_purchase_product::get_the_ID();
$workshopsTmp['workshop_title'] = ECSE_purchase_product::get_the_name();
$workshopsTmp['workshop_time'] = $workshop_data['time'];
$workshopsTmp['workshop_room'] = $workshop_data['room'];
$workshopsTmp['workshop_num_of_tickets'] = ECSE_purchase_product::get_the_QTY();
$workshops[] = $workshopsTmp;
}
I'm trying to pass variable to the view and this one is very weird as the naming and directory structure is correct. Below is the function in my controller:
public function validate_apply_link(){
App::uses('CakeEmail', 'Network/Email');
$this->layout = 'blank';
$listings = $this->CareersAndJob->query("
SELECT l.sid, l.title, lp.value, u.CompanyName, u.WebSite
FROM listings l
LEFT JOIN listings_properties lp
ON lp.object_sid = l.sid
LEFT JOIN users u
ON u.sid = l.user_sid
WHERE l.active = 1
AND lp.add_parameter = 2
AND l.JobGateSenderReference IS NULL
AND u.CompanyName != 'AECOM'
ORDER BY u.CompanyName ASC
LIMIT 5
");
$doc = new DOMDocument();
ob_start();
$listing_count = count($listings);
echo nl2br("Checking $listing_count active jobs...\n\n");
$i=0;
foreach($listings as $listing){
$sid = $listing['l']['sid'];
$url = $listing['lp']['value'];
$company_name = $listing['u']['CompanyName'];
$title = htmlspecialchars($listing['l']['title']);
$length = strpos($title, "-");
if($length != 0){
$title = substr($title, 0, $length-1);
}
$title = substr($title, 0, $length-1);
$title = substr($title, 0, 10);
$data = $this->curl($url);
$check_pdf = strpos($data['info']['content_type'], "pdf");
if($check_pdf != false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$outputs['data'][$i]['data_type'] = 'pdf';
$i++;
continue;
}
#$doc->loadHTML($data['results']);
$html = $doc->saveHTML();
$xpath = new DOMXpath($doc);
$body = $doc->getElementsByTagName('body')->item(0);
$parsed_url = parse_url($url);
switch($parsed_url['host']){
case "www.michaelpage.com.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$ref}')]");
break;
case "https://vacancies.mackay.qld.gov.au":
parse_str($url);
$exist = $xpath->query("//*[contains(#value,'{$title}')]");
break;
default:
$exist = $xpath->query("//*[contains(text(),'{$title}')]");
break;
}
if($exist->length == 0){
if(strpos($url, '#') == false){
$outputs['data'][$i]['url'] = $url;
$outputs['data'][$i]['sid'] = $sid;
$outputs['data'][$i]['title'] = $title;
$outputs['data'][$i]['company_name'] = $company_name;
$outputs['data'][$i]['our_link'] = "http://careersandjobs.com.au/display-job/{$sid}";
$outputs['data'][$i]['content_type'] = $data['info']['content_type'];
$response_code = $this->http_response_codes($data['info']['http_code']);
$outputs['data'][$i]['response_code'] = $response_code;
$outputs['data'][$i]['data_type'] = 'title_not_found';
}else{
$outputs['data'][$i]['data_type'] = 'no_iframe';
}
$i++;
}
flush();
ob_flush();
}
$this->set(compact('outputs'));
}
I can do pr on the outputs variable in the view but this outputs to NULL but when I delete the entire bunch of code inside the controller function and just pass a test variable through it works.
Is there something wrong with the function that I am not aware of?
No errors were found in the above function by the way
app/Controller/CareersAndJobsController.php (line 1048)
array(
'data' => array(
(int) 0 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225055',
'sid' => '3649',
'title' => 'Graduate P',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3649',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 1 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225724',
'sid' => '3726',
'title' => 'Program &a',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3726',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
),
(int) 2 => array(
'url' => 'http://bawbawshire.currentjobs.com.au/cvbuilder/apply+for+this+job/no/1225826',
'sid' => '3727',
'title' => 'Road Netwo',
'company_name' => 'Baw Baw Shire Council',
'our_link' => 'http://careersandjobs.com.au/display-job/3727',
'content_type' => 'text/html; charset=utf-8',
'response_code' => 'OK',
'data_type' => 'title_not_found'
)
)
)
This is what I am getting from outputs variable just before it gets set by the set function in controller
Any reason you chose to use CakePHP? Because you seem to not make use of its functionality!
You're using literal SQL queries, therefore basically skipping the Models functionality.
You're outputting your content from your Controller? Be careful when using output buffering, this may conflict with CakePHP's inner workings, which also relies on output buffering in many cases. Because you're already outputting the content here (ob_flush()), you'll be outputting your content before your View is reached..
Normally I would point to specific points in the manual, however, because there's so much wrong here, I would suggest to start reading at the beginning
I am trying to make and return json data using codeigniter. I want to receive that data in this format
[
{
'title': 'this is title',
'desc': 'THis is desc'
},
{
'title': 'this is title',
'desc': 'THis is desc'
}
]
But I am receiving it this way
[[{"title":"this is title","desc":"this is desc"}],[{"title":"this is title","description":"this is desc"}]]
how can I change this format to above one?
here is my code
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
array(
'title' => $joke->title,
'description' => $joke->joke
)
);
}
echo json_encode($arr);
}
Make the assignment inside foreach as
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
Otherwise you will get a multi-dimensional array for each $joke.
You are adding array of array element each time in a loop. Instead just add single array.
public function v1 () {
$this->load->model('model_jokes');
$jokes = $this->model_jokes->readJokes();
$arr = array();
foreach ($jokes as $joke) {
$arr[] = array(
'title' => $joke->title,
'description' => $joke->joke
);
}
echo json_encode($arr);
}
Try :
echo '<pre>'.json_encode($arr).'</pre>';
i've got the following array:
$comments = array();
$comments[] = array('member_id' => '17',
'time' => '2011-05-10 11:10:00',
'name' => 'John Smith',
'comment' => 'Test Comment 1');
$comments[] = array('member_id' => '25',
'time' => '2011-05-10 11:26:00',
'name' => 'David Jones',
'comment' => 'Test Comment 2');
$comments[] = array('member_id' => '17',
'time' => '2011-05-10 13:15:00',
'name' => 'John Smith',
'comment' => 'Test Comment 3');
How would i go about grouping it by member_id? So I'll be able to display the comments on the page with the following formatting:
John Smith(2 comments)
2011-05-10 11:10:00 | Test Comment 1
2011-05-10 13:15:00 | Test Comment 3
David Jones(1 comment)
2011-05-10 11:26:00 | Test Comment 2
One solution is to sort them by the name field (check out usort for that), but even easier might be to just populate a new array in this way:
$grouped = array();
foreach($comments as $c) {
if(!isset($grouped[$c['name']]) {
$grouped[$c['name']] = array();
}
$grouped[$c['name']][] = $c;
}
//Now it's just a matter of a double foreach to print them out:
foreach($grouped as $name => $group) {
//print header here
echo $name, "<br>\n";
foreach($group as $c) {
//print each comment here
}
}
I would suggest using a second grouping array
$groups[] = array();
foreach( $comment as $k=>$v ) {
$groups[$v['member_id']][] = $k
}
And then to print it
foreach( $group as $m_id=>$arr ) {
echo "Group $m_id<br/>\n";
foreach( $arr as $k ) {
echo $comment[$k]."<br/>\n";
}
}
You should try with taking multi-dimensional array.
$comment_groups[] = array();
$m_id = '';
foreach( $comment_groups as $key=>$val ) {
if($key == 'member_id'){
$m_id = $val;
}
$comment_groups[$m_id]][] = $val;
}
Then you can print as you want to display.