PHP Function Help - php

I've written this piece of code, which outputs the profile_display_fields for the $USER:
$appearance = profile_display_fields($USER->id);
if (empty($appearance)) {
//Do nothing
} else {
foreach ($appearance as $c) {
$custom .= '<a href=\''.$CFG->wwwroot.'/course/view.php?id='.$c->id.'\'>'.$c->fullname.'</a>';
}
}
Here is the function I'm using:
function profile_display_fields($userid) {
global $CFG, $USER;
if ($categories = get_records_select('user_info_category', '', 'sortorder ASC')) {
foreach ($categories as $category) {
if ($fields = get_records_select('user_info_field', "categoryid=$category->id", 'sortorder ASC')) {
foreach ($fields as $field) {
require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
$newfield = 'profile_field_'.$field->datatype;
$formfield = new $newfield($field->id, $userid);
if ($formfield->is_visible() and !$formfield->is_empty()) {
print_row(s($formfield->field->name.':'), $formfield->display_data());
}
}
}
}
}
}
What I'm looking to do is try some var_dumps to output the correct data.
However can anyone help me identify the variables?

In your function you are not returning any value but above that in your code, you have assigned a variable to this function:
$appearance = profile_display_fields($USER->id);
You need to return some variable/data from the function and that is the one to be var dumped.
I suppose you are using the print_row to print the data, not returning the response to be used out of the function.

Related

Adding additional string to variable - PHP

Here's my problem. I want to create a function that takes an outside variable that contains an xpath and once the function runs I want to add to that same variable to create a counter.
So I have the outside variable:
$node = $xmlDoc->xpath('//a:Order');
Then the function with a single argument that will take the outside variable ($node). Like so:
function loopXML($node) {
i=1; //counter variable
}
Now I want to add a counter to $node so that it goes through all of the children of "Order". Outside of the function, I would use:
$child = $xmlDoc->xpath('//a:Order['.$i.']/*');
But inside of the function, I have no idea how to concat it. Does anyone have any idea how I could do this?
EDIT:
Also, it should be noted that I created an arbitrary namespace already:
foreach($xmlDoc->getDocNamespaces() as $strPrefix => $strNamespace) {
if(strlen($strPrefix)==0) {
$strPrefix="a"; //Assign an arbitrary namespace prefix.
}
$xmlDoc->registerXPathNamespace($strPrefix,$strNamespace);
}
SimpleXMLElement::xpath() uses the node associated with the SimpleXML element as the context so you can do something like:
foreach ($xmlDoc->xpath('//a:Order') as $order) {
foreach ($order->xpath('*') as $field) {
...
}
}
But SimpleXMLElement::children() is a list of the element child nodes so it returns the same as the Xpath expression * or to be more exact '*[namespace-uri == ""]'. The first argument is the namespace of the children you would like to fetch.
foreach ($xmlDoc->xpath('//a:Order') as $order) {
foreach ($order->children() as $field) {
...
}
}
This can be easily refactored into a function.
function getRecord(SimpleXMLelement $order, $namespace) {
$result = [];
foreach ($order->children($namespace) as $field) {
$result[$field->getName()] = (string)$field;
}
return $result;
}
You should always depend on the actual namespace, never on the prefix. Prefixes can change and are optional.
Put all together:
$xml = <<<'XML'
<a:orders xmlns:a="urn:a">
<a:order>
<a:foo>bar</a:foo>
<a:answer>42</a:answer>
</a:order>
</a:orders>
XML;
$namespace = 'urn:a';
$orders = new SimpleXMLElement($xml);
$orders->registerXpathNamespace('a', $namespace);
function getRecord(SimpleXMLelement $order, $namespace = NULL) {
$result = [];
foreach ($order->children($namespace) as $field) {
$result[$field->getName()] = (string)$field;
}
return $result;
}
foreach ($orders->xpath('//a:order') as $order) {
var_dump(getRecord($order, $namespace));
}
Output:
array(2) {
["foo"]=>
string(3) "bar"
["answer"]=>
string(2) "42"
}
So I figured it out with a lot of Googling and the help of ThW. So to all that helped, thank you. Here's how I got it to work:
$orderPNode = '//a:Order';
$amazonRawXML = 'AmazonRaw.xml';
$amazonRawCSV = 'AmazonRaw.csv';
function loopXML($xmlDoc, $node, $writeCsv) {
$i = 1;
$xmlDocs = simplexml_load_file($xmlDoc);
$result = [];
foreach($xmlDocs->getDocNamespaces() as $strPrefix => $strNamespace) {
if(strlen($strPrefix)==0) {
$strPrefix="a"; //Assign an arbitrary namespace prefix.
}
$xmlDocs->registerXPathNamespace($strPrefix,$strNamespace);
}
file_put_contents($writeCsv, ""); // Clear contents of csv file after each go
$nodeP = $xmlDocs->xpath($node);
foreach ($nodeP as $n) {
$nodeC = $xmlDocs->xpath($node.'['.$i.']/*');
if($nodeC) {
foreach ($nodeC as $value) {
$values[] = $value;
}
$write = fopen($writeCsv, 'a');
fputcsv($write, $values);
fclose($write);
$values = [];
$i++;
} else {
$result[] = $n;
$i++;
}
}
return $result;
}
loopXML($amazonRawXML, $orderPNode, $amazonRawCSV);

Get form validation errors in Symfony 2.7 as a string

I'm getting a few form errors but i'm struggling to understand what the errors are, hence why the form is invalid. I'm using Symfony 2.7 and getting the errors using;
$errors = $form->getErrors(true, true);
I'd like them as a string so I can pass them to our logging application, however these are currently coming through as <empty>.
Try this (string)$form->getErrors(), otherwise if you don't cast it to a string, it will be a long frightening array which may make no sense at first glance.
If you want to know the total number of errors that have occurred, use this,
$form->count($form->getErrors())
maybe try
$form->getErrorsAsString()
When having trouble to retrieve errors from a form (mostly when several forms are nested), I use these 2 custom utils functions :
public function getErrorMessagesFromUnbubblingForm(\Symfony\Component\Form\FormInterface $form)
{
$errors = array();
foreach ($form->getErrors() as $key => $error) {
$template = $error->getMessageTemplate();
$parameters = $error->getMessageParameters();
foreach ($parameters as $var => $value) {
$template = str_replace($var, $value, $template);
}
$errors[$key] = $template;
}
if ($form->count()) {
foreach ($form as $child) {
if (!$child->isValid()) {
$errors[$child->getName()] = $this->getErrorMessagesFromUnbubblingForm($child);
}
}
}
return $errors;
}
public function getFlatErrorMessagesFromUnbubblingForm(\Symfony\Component\Form\FormInterface $form)
{
$errors = array();
foreach ($form->getErrors() as $error) {
$template = $error->getMessageTemplate();
$parameters = $error->getMessageParameters();
foreach ($parameters as $var => $value) {
$template = str_replace($var, $value, $template);
}
$errors[] = $template;
}
if ($form->count()) {
foreach ($form as $child) {
if (!$child->isValid()) {
$errors = $this->getFlatErrorMessagesFromUnbubblingForm($child);
}
}
}
return $errors;
}

PHP - recursive function foreach

I would to create a recursive function in order to retrieve data from an array and to organize then.
However I have some difficulties to create the right logic. The principle must be apply to any sub level until it ends or nothing is found.
I want to prevent this kind of code by repeating a foreach inside a foreach...:
$cats = get_categories($args);
$categories = array();
foreach($cats as $cat){
$parent = $cat->category_parent;
if ($parent) {
$categories['child'][$parent][$cat->cat_ID] = $cat->name;
} else {
$categories['parent'][$cat->cat_ID] = $cat->name;
}
}
}
if (isset($categories['parent']) && !empty($categories['parent'])) {
foreach($categories['parent'] as $id => $cat){
$new_cats[$id]['title'] = $cat;
if (isset($categories['child'][$id])) {
foreach($categories['child'][$id] as $child_id => $child_cat){
$new_cats[$child_id]['title'] = $child_cat;
$new_cats[$child_id]['parent_id'] = $id;
if (isset($categories['child'][$child_id])) {
foreach($categories['child'][$child_id] as $sub_child_id => $sub_child_cat){
$new_cats[$sub_child_id]['title'] = $sub_child_cat;
$new_cats[$sub_child_id]['parent_id'] = $child_id;
}
}
}
}
}
}
}
May be this code help you to get idea for formatting your desired array format.
<?php
// Main function
function BuildArr($arr)
{
$formattedArr = array();
if(!empty($arr))
{
foreach($arr as $val)
{
if($val['has_children'])
{
$returnArr = SubBuildArr($val['children']); // call recursive function
if(!empty($rs))
{
$formattedArr[] = $returnArr;
}
}
else
{
$formattedArr[] = $val;
}
}
}
return $formattedArr;
}
// Recursive Function( Build child )
function SubBuildArr($arr)
{
$sub_fortmattedArr = array();
if(!empty($arr))
{
foreach($arr as $val)
{
if($val['has_children'])
{
$response = SubBuildArr($val['children']); // call recursive
if(!empty($response))
{
$sub_fortmattedArr[] = $response;
}
}
else
{
$sub_fortmattedArr[] = $arr;
}
}
return $sub_fortmattedArr;
}
}
?>
I use this code for my previous project for generating categories that upto n-th level

Recursive php menu

I have been searching around for some time but cannot seem to find an answer to my problem.
I have a deep nested array that I need to turn into a nested menu.
https://gist.github.com/anonymous/98e0dcf4f2aef40a1da6
I would like it to end up as something like the following.
https://gist.github.com/anonymous/a0dd4c7d047f11a5ce82
class foo {
function NavigationBuild($routes, $child = false) {
if ($child) {
foreach($routes as $route = > $row) {
if (is_array($row['children'])) {
$output. = self::NavigationBuild($row['children'], true);
} else {
$output. = "<li>".$val['route']."MEEEEE</li>";
}
}
} else {
$output. = '<ul>';
foreach($routes as $route = > $row) {
if (!strlen($row['parent'])) {
$output. = "<li>".$route."</li>";
}
foreach($row['children'] as $key = > $val) {
if (is_array($val['children'])) {
$output. = self::NavigationBuild($val['children'], true);
} else {
$output. = "<li>".$val['route']."MEEEEE</li>";
}
}
}
$output. = '</ul>';
}
return $output;
}
}
Figured it out - seems some sleep was needed.
Thanks to all USEFUL input

How to check with Json or Curl when a page looks empty?

I have a function that loops some data with JSON.
The problem is that weh nmy foreach loop finds this situation here https://graph.facebook.com/search?q=berlusca&limit=10&type=post&until=1327422514 it stops working...
How can I check when the page has empty data??
This is my foreach:
function getPostInfo($url, $lang, $stopwords) {
$j = json_decode(startCurl($url));
foreach($j->data as $v) {
if ($v->type == 'status') {
$post['author_id'][] = $v->from->id;
$post['original_id'][] = $v->id;
$ret['post_url'][] = getPostUrl($original_id, $author_id);
//$description = stopWords($v->message);
$post['description'][] = $v->message;
$post['pub_date'][] = $v->created_time;
}
}
return $post;
}
if (count($j->data) > 0 ) {
foreach ...
}

Categories