set class html attribute to a specific variable within a multidimensional array - php

I have a question that is probably extremely simple, but I just can't get my head around it. And if I'm using the wrong lingo, please let me know....
I'm using a list_helper class to help display a list of records, 1 set per row.
Here is the code I'm working with:
foreach ($records as $record) {
$record_array = get_object_vars($record);
$row = array();
foreach ($fields as $i => $field) {
$value = NULL;
if (isset($field['getter']) && is_callable($field['getter'])) {
$value = call_user_func($field['getter'], $record);
} else if (isset($field['key']) && isset($record_array[($key = $field['key'])])) {
$value = $record_array[$key];
}
if(isset($field['class_attr'])) {
echo $value;
$value->attributes['class'] = 'test';
}
}
}
What I'm trying to achieve (in the last 4 lines of code) is set an HTML class attribute to a specific record. One of the fields (completion_date) has been tagged as having a 'class_attr' value assigned to it in another php page. Something like:
'label' => 'compl_date',
'class_attr' => 'test'
When I echo $value it returns the correct field, but when I want to assign a HTML class attribute to that date field (i.e. completion_date), it returns an
error: Warning: Attempt to modify property of non-object.
This is not code I have written myself, so I'm sure I'm missing something here.
When looking at the $field object, it returns the following details:
Array
(
[0] => Array
(
[label] => Completion date
[class_attr] => testcase
[getter] => Closure Object
(
[this] =>
local_courses_all_current_courses_list Object
(
[model:local_courses_all_current_courses_list:private] =>
local_courses_current_courses_model Object
(
)
[params:local_base_list_helper:private] => Array
(
[action] => 0
[action_arg] =>
[action_confirm] =>
[page] => 0
[per_page] => 30
)
[prefix:local_base_list_helper:private] =>
[display] => local_base_display_helper Object
(
)
)
[parameter] => Array
(
[$record] =>
)
)
)
)
Can anyone point me in the right direction? I have been wrestling with this little thing for over 2 days now and I'm out of options....
Thanks

Related

Looping through JSON output from Hubspot deals API

I am trying to use the Hubspot API (http://developers.hubspot.com/docs/overview) to loop through all deals and find only those which are current and then do something with those deals.
No matter what I try to do I cannot get my head around how I access the data I need - below is an example of the output.
In the API there are lots of items like dealstage below and the value field under these is what I need to access - for example in this case the deal is closedlost. Another example would be amount which would also have an entry in value so I can then see the deal value.
I want to loop through all deals and for each deal get the dealstage, amount, last update, owner and so on. Each of these are contained in an array of the same layout as [dealstage] below with a value
I have gotten to where I can print the dealstage value for each deal but it doesn't really help - is there a better way of doing this?
foreach ($list['deals'] as $line) {
foreach ($line['properties'] as $row => $value) {
if ($row=="dealstage") {
$stage=$value['value'];
print $stage."<br>";
}
}
}
Example array:
Array
(
[deals] => Array
(
[0] => Array
(
[portalId] => 12345
[dealId] => 67890
[isDeleted] =>
[associations] => Array
(
[associatedVids] => Array
(
[0] => 4051
)
[associatedCompanyIds] => Array
(
[0] => 23456
)
[associatedDealIds] => Array
(
)
)
[properties] => Array
(
[dealstage] => Array
(
[value] => closedlost
)
[createdate] => Array
(
[value] => 1471334633784
)
[amount] => Array
(
[value] => 1000
)
Would something like this be what you are looking for. Loop through the array picking out the items you are interested in and place them in a nice simple array for you to use later when building your email.
$for_email = array();
foreach ($list['deals'] as $line) {
$t = array();
if (isset($line['properties']['dealstage']['value'])) {
$t['dealstage'] = $line['properties']['dealstage']['value'];
}
if (isset($line['properties']['amount']['value'])) {
$t['amount'] = $line['properties']['amount']['value'];
}
if (isset($line['properties']['createdate']['value'])) {
$t['createdate'] = $line['properties']['createdate']['value'];
}
// any other data you want to capture
// put this data in the new array
$for_email[] = $t;
}
// check what the new array looks like
print_r($for_email);

Syntax for reading an array in php

I have an array, stored in $array, that with
print "<pre>";
print_r($array);
print "</pre>";
gives an output like this:
Array
(
[device] => Array
(
[0] => Array
(
[#attributes] => Array
(
[name] => Low volt light
[id] => 10
[type] => Z-Wave Switch Multilevel
[value] => 0
[address] => 00016922-018
[code] =>
[canDim] => True
[lastChange] => 26-07-2014 17:31:33
[firstLocation] => Kitchen
[secondLocation] => Main
)
)
[1] => Array
(
[#attributes] => Array
(
[name] => Light
[id] => 11
[type] => Z-Wave Switch Multilevel
[value] => 99
[address] => 00016922-019
[code] =>
[canDim] => True
[lastChange] => 31-07-2014 20:01:05
[firstLocation] => Bedroom
[secondLocation] => Main
)
)
I cannot find my way to access/display for example the value (in this case 0) of device with [id]=>10. What syntax would be the right one in php?
There's not an easy way to do this, without looping through the array.
e.g.
foreach ($array['devices'] as $device) {
if ($device['#attributes']['id'] === $idBeingSearchedFor) {
// Do something with $device.
}
}
Due to the #attributes array key, I'm guessing that this came from XML at some point: You might consider using Simple XML to parse it instead, as you could potentially use XPath then, which does support this type of access.
Alternatively again, you could reformat the array so it could be easily accessed by ID.
For example:
$formattedArray = array();
foreach ($array['devices'] as $device) {
$id = $device['#attributes']['id'];
$formattedArray[$id] = $device;
}
You could then access the device by its ID as follows:
$device = $formattedArray[$idBeingSearchedFor];
You could do it like that:
$id = 10;
$device = array();
foreach($array['device'] as $devices) {
if($devices['#attributes']['id'] == $id) {
$device = $devices['#attributes'];
break;
}
}
echo $device['value'];
Looks like SimpleXML, and if that is the case then those arrays are actually objects that, when put through print_r, look just like arrays. To access them, do the following:
Get straight to the data:
$name = $array->device[0]->attributes()->name;
Or loop through each of the attributes in the first device:
foreach ($array->device[0]->attributes() as $key => $value) {
// Do something with the data. $key is the name of the
// attribute, and then you have the $value.
}
Or you could loop through all the devices:
foreach ($array->device as $device) {
foreach ($device->attributes() as $key => $value) {
// Do something
}
}
It's simple ... try below...
print $array['device'][0]['#attributes']['id'];
or
print $array['device']['0']['#attributes']['id'];

Function in_array() - Look for values in multidimensional object array

I'm facing a bit of a problem I can't fix myself.
What I'm trying to achieve is sort of a search filter. I have an array which can variate between 1 row to +100 rows.
The array is built like this:
Array
(
[0] => Array
(
[0] => PK customer
[1] => Call number
[2] => Subject of the call
[3] => Date created
[4] => Date changed
)
)
Here is a real version of one of my array's:
stdClass Object ( [ReadOpenCallsResult] => stdClass Object (
[ArrayOfstring] => Array
(
[0] => stdClass Object (
[string] => Array
(
[0] => 180355
[1] => C0000448207
[2] => TESTDOC
[3] => 3-7-2013 14:20:14
[4] => 3-7-2013 14:20:14
)
[1] => stdClass Object (
[string] => Array
(
[0] => 180355
[1] => C0000448209
[2] => TESTDOC
[3] => 2-7-2013 14:20:14
[4] => 2-7-2013 14:20:14
)
)
I have a WCF webservice which generates an array of the result of a function in C# and then sends it to my PHP page.
Now I was testing the in_array function, it works perfectly with an easy array but I can't seem to make it work with a multidimensional array.
I store my array into $_SESSION['searchCalls']
I tested with all kinds of array's but I can't get the 'real' array to work.
I tried it this way:
$key = array_search('180335',$_SESSION['searchCalls']);
And this way
if (in_array('180335',$_SESSION['searchCalls']))
EDIT: I saw some really good examples, but.. is it possible to get all the values in the sub array when someone looks for 'C0000448207' and then get the subject of the call and the datecreated with it?
This is the function which generates the object arrays.
public List<List<string>> ReadOpenCalls(int relation)
{
RidderIQSDK IQSDK = new RidderIQSDK();
SDKRecordset inboundSet = IQSDK.CreateRecordset("R_ACTIONSCOPE", "PK_R_ACTIONSCOPE, DESCRIPTION, DATECREATED, DATECHANGED, CODE", "FK_RELATION = " + relation, "DATECREATED DESC ");
var messages = new List<List<string>>();
List<string> mess = new List<string>();
if (inboundSet != null && inboundSet.RecordCount > 0)
{
inboundSet.MoveFirst();
do
{
List<string> list = new List<string>();
string pkas = inboundSet.Fields["PK_R_ACTIONSCOPE"].Value.ToString();
string code = inboundSet.Fields["CODE"].Value.ToString();
string descr = inboundSet.Fields["DESCRIPTION"].Value.ToString();
string datecreated = inboundSet.Fields["DATECREATED"].Value.ToString();
string datechanged = inboundSet.Fields["DATECREATED"].Value.ToString();
list.Add(pkas);
list.Add(code);
list.Add(descr);
list.Add(datecreated);
list.Add(datechanged);
messages.Add(list);
inboundSet.MoveNext();
}
while (!inboundSet.EOF);
return messages;
}
mess.Add(null);
messages.Add(mess);
IQSDK.Logout();
return messages;
}
I solved it myself already, this is my solution which is kinda nasty but it works.
$roc = array('relation' => $_SESSION['username']);
$rocresponse = $wcfclient->ReadOpenCalls($roc);
$_SESSION['searchCalls'] = $rocresponse;
foreach ($rocresponse->ReadOpenCallsResult as $key => $value){
if (count($value) === 0) {
}
if (count($value) === 1) {
foreach ($value as $key1 => $value1){
if (in_array($searchWord,$value1)){
echo "Value is in it";
}
}
}
else{
foreach($value as $key1 => $value1){
foreach($value1 as $key2 => $value2){
if (array_search($searchWord,$value2)){
print_r($value2);
}
}
}
}
}
I'm always interested in better solutions, and maybe this solution can help someone else out too.
As pointed out by Nisarg this isn't an Array its an Object. Or you need to update your question to show you are accessinng the object.
What if you try something like this
$SearchCalls = $_SESSION['searchCalls'];
if (in_array('180335',$SearchCalls->ReadOpenCallsResult)){
//do some work.
}

PHP Accessing named array elements issue

I have an array which is generated from an XML file and it shows me like below when printed with print_r
Array
(
[cxname] => Global CX 87 123
[ipaddress] => 66.240.55.87
[slots] => Array
(
[slot] => Array
(
[0] => Array
(
[slotno] => 1
[cardtype] => 0x24
[modelno] => OP3524J
[label1] => OP
[label2] => Module
[severity] => Minor
)
[1] => Array
(
[slotno] => 2
[cardtype] => 0x25
[modelno] => OP3524K
[label1] => OP
[label2] => Module
[severity] => Major
)
)
)
)
When I print like this, it shows nothing
echo $dataArray->cxname;
But following code works and prints "Global CX 87 123 "
echo $dataArray["cxname"];
How can I make it work as above example.
Just do this:
$dataArray = (object)$dataArray;
It'll convert the array in an stdClass object and allow you to use it that way. Please note that this will only convert the first level for the array. You'll have to create a function to recurse through the array if you want to access all levels that way. For example:
<?php
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
For more information, have a look at http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass. To find out about typecasting, you can also read http://www.php.net/manual/en/language.types.object.php#language.types.object.casting.
This:
echo $dataArray["cxname"];
is the way you access array elements. But this:
echo $dataArray->cxname;
is the way, you access class members.
If you want to access the data as class members, you have to use a xml parser which returns classes (or objects), not arrays.
If you have got the XML string, you can parse it into an object by using simplexml_load_string().

Drupal-6: Why won't this node save?

I have constructed a set of nodes. After running them through node_save(), I get back an nid, and I can navigate to the page for that node, but they are empty. (No data is shown for any of the fields.)
When I go to the edit url for that node, I get this error message:
warning: call_user_func_array()
[function.call-user-func-array]: First
argument is expected to be a valid
callback, 'Bout_node_form' was given
in
/home/odp/public_html/includes/form.inc
on line 367.
Here is the print_r() of one node I am trying to save:
stdClass Object
(
[type] => Bout
[name] => Gary Oak
[title] => Bout - 0
[promote] => 1
[comment] => 2
[revision] =>
[format] => 0
[status] => 0
[field_weapon] => Array
(
[0] => Array
(
[value] => foil
)
)
[field_fencer] => Array
(
[0] => Array
(
[uid] => 3
)
)
[field_touches_scored] => Array
(
[0] => Array
(
[value] => 4
)
)
[field_meet] => Array
(
[0] => Array
(
[nid] => Drew
)
)
[field_round] => Array
(
[0] => Array
(
[value] => 1
)
)
[field_legacy_bout] => Array
(
[0] => Array
(
[value] => no
)
)
[teaser] =>
[uid] => 1
[created] => 1262732370
[validated] => 1
)
These nodes have all been run though node_validate(), and presumably that would have caught some errors. Also, this node is missing required taxonomy, but that isn't causing any error messages, either.
This is how node_validate() was called:
function preview_validate($form, &$form_state) {
$nodes_to_save = construct_nodes();
foreach ($nodes_to_save as $node) {
node_validate($node, $form);
if ($errors = form_get_errors()) {
form_set_error('', t('Validation error. No nodes saved.'));
}
}
$_SESSION[CONSTRUCTED_KEY] = $nodes_to_save;
}
This is where the error is coming from, in the core file includes/form.inc:
// If $callback was returned by a hook_forms() implementation, call it.
// Otherwise, call the function named after the form id.
$form = call_user_func_array(isset($callback) ? $callback : $form_id, $args);
The node shows up in the node table, but not the content_type_bout table.
This is the construct_nodes() function:
function construct_nodes() {
global $user;
$file = unserialize($_SESSION[FILE_KEY]);
$count = 0; // how many nodes have been created?
$success = TRUE; // have all the nodes thus far validated?
foreach ($file->parsed as $node) {
$odp = new StdClass();
$odp->type = $_SESSION[NODE_TYPE_KEY];
if (! in_array('name', $file->matched_keys)) {
$odp->name = $user->name;
}
if (! in_array('title', $file->matched_keys)) {
$odp->title = sprintf("%s - %s", $_SESSION[NODE_TYPE_KEY], $count);
}
$node_type_default = variable_get('node_options_'. $_SESSION[NODE_TYPE_KEY], array('status', 'promote')); //copied from blogapi module
$odp->promote = in_array('promote', $node_type_default);
$odp->comment = variable_get('comment_'. $_SESSION[NODE_TYPE_KEY], 2);
$odp->revision = in_array('revision', $node_type_default);
$odp->format = FILTER_FORMAT_DEFAULT;
$odp->status = CTN_DEFAULT_PUBLISHED;
// this makes the assumption that the field arrays will always have only one item
// doesn't handle taxonomy
foreach ($node as $field => $value) { // $field => value: [Touches scored] => 5
$node_key = $file->matched_keys[$field]; // $node_key will be something like: "field_meet" or "vid:4"
$vid = vidOfTaxKey($node_key);
if ($vid == NULL) {
$valTypes = $_SESSION[SAMPLE_NODE_KEY]->$node_key; // like: [0] => Array ( [uid] => 3 )
$valType = array_keys($valTypes[0]);
$odp->$node_key = array(array($valType[0] => $value));
}
}
$to_save[] = $odp;
$count++;
unset($submitted_odp);
}
return $to_save;
}
bout is a CCK-defined content type. Using the human name "Bout" for the type instead of the internal code name bout was, I believe, a source of error.
where is this custom content type defined? in a custom module, or via Administer > Content > Content types > Add content type? is it defined at all? if not, then no wonder you get this error: how is Drupal supposed to know what this content type is composed of and how to render its view and edit forms? try defining it, either way.
custom content (node) type names ([type] => Bout) must contain only lowercase letters, numbers, and underscores. try changing Bout to bout.
see also How do I create a node from a cron job in drupal? and http://drupal.org/node/178506#comment-895418 (the whole thread).
try this
<?php
$new_blognode = new stdClass();
$new_blognode->type = 'blog';
module_load_include('inc', 'node', 'node.pages');
$output .= drupal_get_form('blog_node_form', $new_blognode);
?>
note that you should change this to your needs
$node['type']='bout'; NOT $node['type']='Bout';
Confirm that you are not struck with simple caps problem.

Categories