I am not really familiar on how php handles array, in .NET I can access array using this method
array[x][y];
My question is:
I am retrieving records from the database and returning it to the $res_merchant_field
$res_merchant_field = $this->CI->merchantfield_model->merchantfield_list( $str_where );
and $res_merchant_field will be populated with this record:
Array
(
[0] => stdClass Object
(
[MFID] => 1
[MFName] => Bill No
[FTID] => 1
[DTID] => 1
[MFRequired] => 1
[MFDefaultValue] =>
[MFDueDate] => 0
[MFToBePaid] => 0
[MFMaxLength] => 12
[MFOrderNo] => 1
[MFStatus] => 1
)
[1] => stdClass Object
(
[MFID] => 2
[MFName] => Gallons Consumed
[FTID] => 1
[DTID] => 2
[MFRequired] => 1
[MFDefaultValue] =>
[MFDueDate] => 0
[MFToBePaid] => 0
[MFMaxLength] => 5
[MFOrderNo] => 2
[MFStatus] => 1
)
[2] => stdClass Object
(
[MFID] => 3
[MFName] => Amount Due
[FTID] => 3
[DTID] => 1
[MFRequired] => 1
[MFDefaultValue] =>
[MFDueDate] => 0
[MFToBePaid] => 1
[MFMaxLength] => 15
[MFOrderNo] => 3
[MFStatus] => 1
)
)
How can I access and fetch the record from that array with this condition:
it will look through all the array find specific index, lets say index 0 which is MFID,
after getting the MFID and comparing it with another variable, if it is true,
it will get the DTID for that array MFID.
example:
get MFID = 1, the DTID will be 1, if I get the MFID = 3, the DTID will be 1.
or how can I access the array like $array[x][y]?
Thanks in advance.
The problem is that the second level is not an array but instead an object, to access a property you will have to use this format.
$array[$x]->$y;
Unfortunately you cannot access a property by an index do o get the MFID of the 0th Item you will need to say
$array[0]->MFID;
Related
I have written a sql query which returns an object. Having used the object in my view file, I now need to convert it to an array so that I can remove the duplicate entries.
To covert the object to an array, I am using,
$arr = (array)$object_name;
Here is the result.
Array
(
[0] => stdClass Object
(
[id] => 1
[body_parts_id] => 2
[conditions_id] => 1
[priorities_id] => 1
[name_of_body_part] => Lungs and airways
[name_of_condition] => Unconscious, not breathing or responding.
[priority_title] => Priority One
)
[1] => stdClass Object
(
[id] => 1
[body_parts_id] => 1
[conditions_id] => 1
[priorities_id] => 1
[name_of_body_part] => Heart and blood vessels
[name_of_condition] => Unconscious, not breathing or responding.
[priority_title] => Priority One
)
[2] => stdClass Object
(
[id] => 1
[body_parts_id] => 1
[conditions_id] => 2
[priorities_id] => 1
[name_of_body_part] => Heart and blood vessels
[name_of_condition] => Signs of a heart attack
[priority_title] => Priority One
)
[3] => stdClass Object
(
[id] => 1
[body_parts_id] => 1
[conditions_id] => 3
[priorities_id] => 1
[name_of_body_part] => Heart and blood vessels
[name_of_condition] => Heavy bleeding that won't stop
[priority_title] => Priority One
)
[4] => stdClass Object
(
[id] => 2
[body_parts_id] => 3
[conditions_id] => 4
[priorities_id] => 2
[name_of_body_part] => Muscle, bone and joint
[name_of_condition] => Condition test 1
[priority_title] => Priority Two
)
)
The problem comes when I try and now loop through the array to remove any duplication. I get the message.
Cannot use object of type stdClass as array
Clearly I am not converting the Object to an Array correctly.
Can someone help please - thank you.
To covert the object to an array you should change
$arr = (array)$object_name;
To this instead
$arr = json_decode($object_name, true);
Read more https://www.php.net/manual/en/function.json-decode.php
I'm a newbie in PHP object. so I want to make random forest classification. I have a problem to print out the tree decision tree in my classification.
in this case my result classification :
[tree:protected] => Phpml\Classification\DecisionTree\DecisionTreeLeaf Object
(
[value] => <= 3.45
[numericValue] => 3.45
[operator] => <=
[columnIndex] => 1
[leftLeaf] =>
[rightLeaf] =>
[records] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[classValue] => late
[isTerminal] => 1
[isContinuous] => 1
[giniIndex] => 0.44444444444444
[level] => 0
)
how can I just print 3.45, the colomindex=1, late, the gini index, and the level?
I want to use that value to build a decision tree.
I'm not sure if this answers your question but from my understanding, you would need to create an array like so: $tree = ["key" => "value"]; and then echo $tree["key"];
So I decoded my json, and I get this array out of it
Array (
[totalstreams] => 1
[activestreams] => 1
[currentlisteners] => 0
[peaklisteners] => 2
[maxlisteners] => 100
[uniquelisteners] => 0
[averagetime] => 0
[version] => 2.4.0.147 (posix(linux x64))
[streams] => Array ( [0] => Array (
[id] => 1
[currentlisteners] => 0
[peaklisteners] => 2
[maxlisteners] => 100
[uniquelisteners] => 0
[averagetime] => 0
[servergenre] => Misc
[serverurl] => http://example.com
[servertitle] => Van Den Berg Stream
[songtitle] => Katy Perry - This Is How We Do
[streamhits] => 3
[streamstatus] => 1
[backupstatus] => 0
[streampath] => /stream
[streamuptime] => 1998
[bitrate] => 128
[content] => audio/mpeg ) ) )
I got to this using:
print_r($json)
I'm interested in the songtitle part, so normally I'd go:
$json['streams']['songtitle'];
But it just throws a Undedefined index error.
Do you huys know what I do wrong?
$json['streams'][0]['songtitle'];
That is what you want. Look carefully at your print_r results again, you'll notice the following after streams:
[streams] => Array ( [0] => Array (
You need to take that 0 into account.
I have this:
print_r($response["member"]);
I need to retrieve name under levels, it's at the bottom, how should I write it:
I thought of $response["member"][0]["Sequential"]["levels"]...? Also this number under levels wont be always the same.
Thank you!
Array
(
[0] => Array
(
[ID] => 1
[UserInfo] => Array
(
[ID] => 1
[caps] => Array
(
[administrator] => 1
)
[cap_key] => wp_capabilities
[roles] => Array
(
[0] => administrator
)
[allcaps] => Array
(
[switch_themes] => 1
[edit_themes] => 1
[activate_plugins] => 1
[edit_plugins] => 1
[edit_users] => 1
[edit_files] => 1
[manage_options] => 1
[moderate_comments] => 1
[manage_categories] => 1
[manage_links] => 1
[upload_files] => 1
[import] => 1
[unfiltered_html] => 1
[edit_posts] => 1
[edit_others_posts] => 1
[edit_published_posts] => 1
[publish_posts] => 1
[edit_pages] => 1
[read] => 1
[level_10] => 1
[level_9] => 1
[level_8] => 1
[level_7] => 1
[level_6] => 1
[level_5] => 1
[level_4] => 1
[level_3] => 1
[level_2] => 1
[level_1] => 1
[level_0] => 1
[edit_others_pages] => 1
[edit_published_pages] => 1
[publish_pages] => 1
[delete_pages] => 1
[delete_others_pages] => 1
[delete_published_pages] => 1
[delete_posts] => 1
[delete_others_posts] => 1
[delete_published_posts] => 1
[delete_private_posts] => 1
[edit_private_posts] => 1
[read_private_posts] => 1
[delete_private_pages] => 1
[edit_private_pages] => 1
[read_private_pages] => 1
[delete_users] => 1
[create_users] => 1
[unfiltered_upload] => 1
[edit_dashboard] => 1
[update_plugins] => 1
[delete_plugins] => 1
[install_plugins] => 1
[update_themes] => 1
[install_themes] => 1
[update_core] => 1
[list_users] => 1
[remove_users] => 1
[add_users] => 1
[promote_users] => 1
[edit_theme_options] => 1
[delete_themes] => 1
[export] => 1
[administrator] => 1
)
[filter] =>
[user_login] => admin
[user_nicename] => admin
[user_email] => goranefbl#gmail.com
[user_url] =>
[user_registered] => 2014-01-29 10:57:09
[user_activation_key] =>
[user_status] => 0
[display_name] => admin
[wlm_feed_url] => http://pialarson.com/excel/feed/?wpmfeedkey=1;2e7e48ca65d94e5f0ec1baae46e4972c
[wpm_login_date] => 1392155735
[wpm_login_ip] => 62.68.119.252
)
[Sequential] =>
[Levels] => Array
(
[1391447566] => stdClass Object
(
[Level_ID] => 1391447566
[Name] => Team Membership
[Cancelled] =>
[CancelDate] =>
[Pending] =>
[UnConfirmed] =>
[Expired] =>
[ExpiryDate] => 1393866766
[SequentialCancelled] =>
[Active] => 1
[Status] => Array
(
[0] => Active
)
[Timestamp] => 1391447566
[TxnID] => WL-1-1391447566
)
)
[PayPerPosts] => Array
(
)
)
)
An answer might be to use array_walk_recursive by following the official documentation:
http://www.php.net/manual/en/function.array-walk-recursive.php
<?php
$properties = new stdClass();
$properties->names = [];
function extractNames($levels, $key, $properties) {
if (
is_object($levels) &&
array_key_exists('Name', get_object_vars($levels)) &&
array_key_exists('Level_ID', get_object_vars($levels))
) {
$properties->names[] = $levels->Name;
}
}
array_walk_recursive($response, 'extractNames', $properties);
echo print_r($properties, true);
<?php
$nameInFirstLevelsElement = current($response["member"][0]["levels"])->Name
?>
This should work to retrieve the Name from the first levels element.
That empty space next to "Sequential" means it doesn't have a value. So that's not the one you're looking for.
Furthermore, one of those levels indicates "stdClass object", which means you can access its members via the -> operator.
Let's strip away everything that doesn't matter for a minute. I think it'll help you understand the data structure:
Array
(
[0] => Array
(
[Levels] => Array
(
[1391447566] => stdClass Object
(
[Level_ID] => 1391447566
[Name] => Team Membership
)
)
)
)
So this will work:
$object = $response["member"][0]["Levels"][1391447566];
$name = $object->Name;
Edit
If the index of Levels changes every time, then pull it apart a little bit more...
$levels = $response["member"][0]["Levels"];
$firstLevel = array_shift(array_values($levels));
$name = $firstLevel->Name;
See here for a good answer on getting the first element out of the $levels array: https://stackoverflow.com/a/3771228/266374
If the number under the 'Levels' array won't be the same, you can use a foreach to pull out the 'Name' information.
foreach ($response[0]['Levels'] AS $level_key => $level_val) {
$level_name = $level_key->Name;
}
echo 'Name: '.$level_name;
If there is only going to be one element, then it will grab it. If there are multiple numbers under 'Levels', then it will loop through them and assign each one to '$level_name', overwriting any previous assignments. In other words, only the last one it finds will be captured.
EDIT:
In the example, I mistakenly tried to grab the Name from the $key instead of the $val. This is the correct method:
foreach ($response[0]['Levels'] AS $level_key => $level_val) {
$level_name = $level_val->Name;
}
echo 'Name: '.$level_name;
Here is a demo of the working code
I am trying to query some data from the moodle database. I am using the data manipulation API. Here is my code. When I run it on the browser, i get a blank screen. i reall dont know what the $enrolids is. Is it an associative array or what. Even when I try create an associative array, I still get a blank screen.
<?php
require_once("../config.php");
$userid=$_GET['userid'];
//Get the enrolids from the mdl_user_enrolments table
$enrolids=$DB->get_records_sql('SELECT enrolid FROM {user_enrolments} WHERE userid=?', array($userid));
echo $enrolids['enrolid'];
?>
Will appreciate the help....
I figured it out:
To anyone with the same problem. Here is the solution.
Moodle is object oriented. Meaning, the queries made, return an Array of stdclass objects i.e:
Array ( [1] => stdClass Object ( [id] => 1 [status] => 0 [enrolid] => 5 [userid] => 3 [timestart] => 0 [timeend] => 2147483647 [modifierid] => 0 [timecreated] => 0 [timemodified] => 0 ) [2] => stdClass Object ( [id] => 2 [status] => 0 [enrolid] => 6 [userid] => 3 [timestart] => 0 [timeend] => 2147483647 [modifierid] => 0 [timecreated] => 0 [timemodified] => 0 ) )
Use the -> notation to fetch whatever value you desire i.e If the above array is stored in a variable e.g. $arr, do the following to access status for example
$arr[1]->status;
CHEERS....