Get variables from several interrelated functions in PHP - php

I'm trying to get variables from several interrelated functions during XML parsing and put them into arrays. The code is:
function readChapters($reader) {
while($reader->read()) {
if( /* condition here */ ) {
$chapter = readValue($reader);
}
if( /* condition here */ ) {
readModules($reader);
}
if( /* condition here */ ) {
return;
}
}
}
function readModules($reader) {
while($reader->read()) {
if( /* condition here */ ) {
readModule($reader);
}
if( /* condition here */ ) {
return($reader);
}
}
}
function readModule($reader) {
while($reader->read()) {
if( /* condition here */ ) {
$topic = readValue($reader);
}
if( /* condition here */ ) {
$description = readValue($reader);
}
}
}
function readValue($reader) {
while($reader->read()) {
if( /* condition here */ ) {
return $reader->readInnerXML();
}
}
}
$reader = new XMLReader();
$reader->open('example.xml');
$current = 0;
$topics_list = array();
$chapterName = ""; // want to add $chapter
$topicName = ""; // want to add $topic
$descriptionText = ""; // want to add $description
while($reader->read()) {
if(// condition here) {
readChapters($reader);
}
$topics_list[$current] = array();
$topics_list[$current]['chapter'] = $chapterName;
$topics_list[$current]['topic'] = $topicName;
$topics_list[$current]['description'] = $descriptionText;
}
$reader->close();
print_r($topics_list);
Problem: How to get $chapter, $topic, $description variables from outside of these functions in order to put them into arrays? Thanks in advance.
Update: The XML document structure is here, and the expected structure of Array():
Array (
[0] => Array (
[chapter] => Chapter_name1
[topic] => Topic_name1
[description] => Content_of_the_topic1
)
[1] => Array (
[chapter] => Chapter_name1
[topic] => Topic_name2
[description] => Content_of_the_topic2
)
[2] => Array (
[chapter] => Chapter_name2
[topic] => Topic_name2
[description] => Content_of_the_topic2
)
.....
)

You're essentially using a set of function to build a data structure using data from an XML object. That means that each function should return the data structure it's named for: readChapters() should return a chapter structure (and should probably be named readChapter(), since I think it's only reading one chapter, correct?), and so on. I don't know what your XML looks like or what your desired data structure looks like, but you'll want something like this:
function readChapter($reader) {
$chapter = array();
while (// condition) {
if (// something)
$chapter['chapter'] = readValue($reader);
elseif (// something else)
$chapter['topic'] = readValue($reader);
// etc
}
return $chapter;
}
Then in your main loop below, you can have this:
while ($reader->read()) {
if (// condition here) {
$topics_list[] = readChapter($reader);
}
}
Hope that gets you closer to something you can build!

Related

Whenever comment on any issue, last comment username not update in issues

Whenever comment on any one of the issues, comment save successfully.
Comment saving code in given below:
$user = elgg_get_logged_in_user_entity();
$p_url = parse_url($_SERVER['HTTP_REFERER']);
if($p_url['path'] == '/issues/view' || $p_url['path'] == '/issues/respond')
$tracker_comment = TRUE;
else
$tracker_comment = FALSE;
if($tracker_comment)
{
action_gatekeeper();
// Get input
$entity_guid = (int) get_input('entity_guid');
$comment_text = get_input('generic_comment');
// Let's see if we can get an entity with the specified GUID
if ($entity = get_entity($entity_guid)) {
$comment = new ElggComment();
$comment->description = $comment_text;
$comment->owner_guid = $user->getGUID();
$comment->container_guid = $entity->getGUID();
$comment->access_id = $entity->access_id;
$guid = $comment->save();
// If posting the comment was successful, say so
if ($guid) {
system_message(elgg_echo("generic_comment:posted"));
} else {
register_error(elgg_echo("generic_comment:failure"));
}
} else {
register_error(elgg_echo("generic_comment:notfound"));
}
// Forward to the
forward($entity->getURL());
}
else
RETURN TRUE;
I am unable to retrieve the last comment username not updated in list of issues. I am using elgg_get_annotation() to retrieve the last comment details.
But not retrieving the details. Last comment code in given bellow.
if ($table_rows) {
foreach ( $table_rows as $entity ) {
if ($entity->unread == 1) {
$unread = "Yes";
} else {
$unread = "No";
}
if ($entity->assigned_to == 0) {
$assigned = "No";
} else {
$assigned = "Yes";
}
$last_options = array ();
$comments = elgg_get_annotations(array(
'annotation_names' => 'issue_tracker_changes',
'guid' => $entity->guid,
'limit' => 1,
'order_by' => 'n_table.id DESC',
));
foreach ( $comments as $comment ) {
$last_comment = get_entity ( $comment->owner_guid );
}
Comments are no longer annotations since Elgg 1.9 but entities. You are creating comment using ElggComment class that represents entity so you're using Elgg 1.9 or newer. You just need to use elgg_get_entities instead of elgg_get_annotations. Use type object and subtype comment.

Invalid argument supplied for foreach() since updating my Customizr theme

I just updated my Customizr child theme and I'm getting the following error on my dashboard:
Warning: Invalid argument supplied for foreach() in /home/beaufort/public_html/wp-content/themes/customizr/inc/class-fire-utils.php on line 653
This is what is on line 653:
foreach ( $_font_groups as $_group_slug => $_font_list ) {
and this is what follows:
if ( 'list' == $_what ) {
$_to_return[$_group_slug] = array();
$_to_return[$_group_slug]['list'] = array();
$_to_return[$_group_slug]['name'] = $_font_list['name'];
}
I am clueless when it comes to php so your help would be much appreicated!
Many thanks
/**
* #return an array of font name / code OR a string of the font css code
* #parameter string name or google compliant suffix for href link
*
* #package Customizr
* #since Customizr 3.2.9
*/
function tc_get_font( $_what = 'list' , $_requested = null ) {
$_to_return = ( 'list' == $_what ) ? array() : false;
$_font_groups = apply_filters(
'tc_font_pairs',
TC_init::$instance -> font_pairs
);
foreach ( $_font_groups as $_group_slug => $_font_list ) {
if ( 'list' == $_what ) {
$_to_return[$_group_slug] = array();
$_to_return[$_group_slug]['list'] = array();
$_to_return[$_group_slug]['name'] = $_font_list['name'];
}
foreach ( $_font_list['list'] as $slug => $data ) {
switch ($_requested) {
case 'name':
if ( 'list' == $_what )
$_to_return[$_group_slug]['list'][$slug] = $data[0];
break;
case 'code':
if ( 'list' == $_what )
$_to_return[$_group_slug]['list'][$slug] = $data[1];
break;
default:
if ( 'list' == $_what )
$_to_return[$_group_slug]['list'][$slug] = $data;
else if ( $slug == $_requested ) {
return $data[1];
}
break;
}
}
}
return $_to_return;
}
Before line 653 add if (is_array($_font_groups)) {
Then, add a closing bracket } above return $_to_return;

get data from array in cakephp

I'm trying to get the data from array in my controller php on Cakephp.
I have this function:
public function updateUserStatus() {
if(isset($this->params['url']["pcs"])) {
$uus = array( "pcs" =>$this->params['url']["pcs"] );
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
And I want to get the data from status_id who have this response:
Array (
[0] => Array
(
[status_id] => 2
)
[1] => Array
(
[rem_time] => 66
)
)
How can I do it?
My question is how can i get the data for status_id ?
public function updateUserStatus() {
if (isset($this->params['url']["pcs"])) {
$uus = array("pcs" =>$this->params['url']["pcs"]);
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$currentStatus = 0;
if (is_array($trans) && isset($trans['status_id'])) {
$currentStatus = $trans['status_id'];
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
public function updateUserStatus($uus){
if(isset($uus["pcs"])) {
$sql = "SELECT status_id as status_id , rem_time as rem_time FROM phones WHERE pcs = '".$uus["pcs"]."' LIMIT 1";
$query = $this->query($sql);
return $query[0]['phones'];
} else {
return "failed";
}
}
Notice, we are returning $query[0]['phones'].
Let me know if it works.
The code could also use some refactoring.
For example, why is the function called updateUserStatus if it is only returning the result of a query? It should also always return an array, for consistency.

Unset Not Clearing Array Key/Value

I have form submission that redirects based on the results of a survey. On the landing page, I call a function to process query string, query the database and return results as an array for in-page processing.
function surveyResults() {
if($goodtogo) {
$survey = $wpdb->get_results(...,ARRAY_A);
$name_has_space = strpos(trim($q_name_field[0]),' ');
if($name_has_space === false) {
$q_first_name = $q_name_field[0];
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
} else {
$q_first_name = substr(trim($q_name_field[0]),0,$name_has_space);
$name_has_num = preg_match('/[0-9]/',$q_first_name);
$q_first_name = ((0 === $name_has_num) ? " ".ucfirst($q_first_name).", " : '');
}
$survey['name']['q_fname'] = $q_first_name;
$results = $survey;
} else {
$results = false;
}
return $results;
}
Output:
Array (
[0]=> Array (
'key' => 'value'
)
...
[n]=> Array (
'key' => 'value'
)
['name'] => Array (
[q_fname] => MyName
)
)
Which is perfect – except – each time I test the page, the $survey[0-n] results change as queried, but the $survey['name']['q_fname'] still holds the previous value MyName.
I have tried adding unset($survey['name']['q_fname']); immediately after setting $results = $survey; but that doesn't seem to make a difference. Do I need to unset($results) or use a reference &$fname...
What am I missing here?
Thanks
I'm macgregor, and I'm an idiot. Missed a critical piece of condition in the query.

Looping class, for template engine kind of thing

I am updating my class Nesty so it's infinite but I'm having a little trouble.... Here is the class:
<?php
Class Nesty
{
// Class Variables
private $text;
private $data = array();
private $loops = 0;
private $maxLoops = 0;
public function __construct($text,$data = array(),$maxLoops = 5)
{
// Set the class vars
$this->text = $text;
$this->data = $data;
$this->maxLoops = $maxLoops;
}
// Loop function
private function loopThrough($data)
{
if( ($this->loops +1) > $this->maxLoops )
{
die("ERROR: Too many loops!");
}
else
{
$keys = array_keys($data);
for($x = 0; $x < count($keys); $x++)
{
if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
}
}
}
// Templater method
public function template()
{
echo $this->loopThrough($this->data);
}
}
?>
Here is the code you would use to create an instance of the class:
<?php
// The nested array
$data = array(
"person" => array(
"name" => "Tom Arnfeld",
"age" => 15
),
"product" => array (
"name" => "Cakes",
"price" => array (
"single" => 59,
"double" => 99
)
),
"other" => "string"
);
// Retreive the template text
$file = "TestData.tpl";
$fp = fopen($file,"r");
$text = fread($fp,filesize($file));
// Create the Nesty object
require_once('Nesty.php');
$nesty = new Nesty($text,$data);
// Save the newly templated text to a variable $message
$message = $nesty->template();
// Print out $message on the page
echo("<pre>".$message."</pre>");
?>
Here is a sample template file:
Dear <!--[person][name]-->,
Thanks for contacting us regarding our <!--[product][name]-->. We will try and get back to you within the next 24 hours.
Please could you reply to this email to certify you will be charged $<!--[product][price][single]--> for the product.
Thanks,
Company.
The problem is that I only seem to get "string" out on the page... :(
Any ideas?
if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
You need to return from the first if statement.
if(is_array($data[$keys[$x]]))
{
return $this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
This will get you a result back when you recurse. You're only getting "string" back right now because that key is only 1 level deep in your array structure.

Categories