I'm using a framework at work that I'm slightly unfamiliar with and trying to access elements of an object that are stored within an array called $items. I've tried die(print_r($items[0])) to try to get the first element but it says 0 is an undefined index. Here is the result of print_r($items):
Any help is much appreciated. If you have any questions I'll gladly answer because I know this is a bit vague. I think it would take up way too much space to explain how this framework actually works.
I figured out that the first element is 2 and not 0, but I'm still unable to access any of the elements within the object. When I tried print_r($items[2]->fields) it didn't return anything, just a blank page.
I think this is what you want:
$item = current($items);
foreach ($item->fields as $key => $val) {
echo "$key => $val\n";
}
Update:
It seems like you cannot get $item->fields since it is a protected property of Dase_DBO_Project object:
[fields:protected] => Array
I don't see any element with index 0 in your array, only keys 5, 4, 3 and 2. To get the first item from array use current($items) or reset($items).
Your array listed here does not have an index of 0 (For more help look here: http://php.net/manual/en/language.types.array.php)
Rather than attempting to access each item with the index. Why don't you use a foreach?
foreach($items as $item)
{
//Do what you want with each object here
var_dump($item);
}
This will allow you to access each object without using the index. For more information using foreach take a look here: http://us3.php.net/manual/en/control-structures.foreach.php
Cheers!
Related
I'm editing someone else's code here:
foreach($list as $items) {
// displays items names and images etc
}
and within the foreach() loop I can see the name using:
echo $items[0]->name
and looking at the contents of $items it looks like this:
Array ( [0] => stdClass Object ( [id] => 7 [name] => Bench Scales // ..etc..
But I can't seem to reference name outside the loop
$list[0]->name // doesn't work
So I'm kinda stuck at this point when trying to sort by name, Yep I've looked up usort() and am happy with the concept of sorting by name, but am unable to sort this array of objects? by name. Any help most welcome
Above the foreach() loop I tried something like this, but no luck:
function cmp($a,$b) { return strcmp($a->name, $b->name); }
usort($list,"cmp");
This example:
$list[0]->name; // doesn't work
Shouldnt work Remember that when you're inside a foreach, you're one level nested when you access the iterable such as $item. Therefore
Assuming that the array has numeric indicies and that The 0th value in $list is an object this would work:
$list[0][0]->name;
To me (and I'm kind of tired right now) this doesn't look like a sort issue. $list is a collection (obviously) and when you run it through the foreach loop, each iteration is giving you a single object array to work with, which is why your first example works. $list is an array of arrays, so you need one more level of "access" to get what you want.
For example, is this safe?
foreach($opps_data as $k=>$v) {
$opps_data[$k.'_mixed'] = WXU::MixedCase($v);
}
It seems to work fine. Does that mean PHP makes a copy of the array before it starts looping?
Yes, foreach loop operates on a copy of original array. More info about internal behaviour of foreach can be found in this great blog.
foreach() uses iterators. Array is called then iterator is used for pointing to array which was called.
In this case $opps_data is called only once. Iterator will not reference original array it will be working on copy of $opps_data which was called.
I have PHP $_SESSION arrays that have an undefined amount of elements. Is it possible to initialise all the values to 0, or do I have to check whether the value is NULL and then set to 0 every time I check a value?
Edit: I'm sorry for the vagueness of my question.
I have an undefined amount of levels, and I'd like to store all the scores of each level in that array. Currently my amount of levels is fixed, so I am currently just writing:
$_SESSION['totals'] = array(0,0,0,0,0);
And then when adding manipulating the data, I simply increment/add a certain amount to that element.
Now I'd prefer to have the same ease of directly incrementing/adding values to certain elements without needing to check whether a value is NULL or something like that...
Edit 2: edited my code as follows:
$_SESSION['totals'] = array();
if(array_key_exists($row['level']-1,$_SESSION['totals'])){
$_SESSION['totals'][$row['level']-1]++;
}else{
$_SESSION['totals'][$row['level']-1] = 1;
}
And it seems to work. Thanks fellas!
You can use array_fill_keys function to fill an array with specified value for defined keys:
$keys = array('foo', 'bar', 'baz');
$output = array_fill_keys($keys, 0);
Defining an array with initial values is defining an array with a length. This does not prevent you from adding or removing elements from the array:
// initial array
$myArray = [0, 0, 0, 0];
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0)
$myArray[] = 1;
print_r($myArray); // would output Array ( [0] => 0 [1] => 0 [2] => 0 [3] => 0 [4] => 1 )
$_SESSION contains only what you put into it. Just make sure you add 0 instead of null the first time you add something.
If you need to do this later, I think your design might be bad. But anyway, $_SESSION is like a normal array, so you can just use PHP's array function to traverse the array and check or change each value.
PHP arrays aren't really arrays you might know from other languages. They really are more like linked lists with hash access.
What this means is: You either know all the string array indices you want to use, and either make sure they exist, or you check their existence every time you access them which might fail.
For numeric indices, the same thing applies. You might have an array with indices 1, 2 and 4 present, but if you run over it with only a for loop, you will trigger a notice when accessing the nonexistant element 3.
Use foreach loops whenever you want to iterate arrays. Check with isset() whenever you want to document that the array value might not be present. Don't do it if you know or assume that the array element MUST be present - if not, you get the notice as a reminder that your code is working on a data structure that is NOT what you thought it is. Which actually is a good thing. Then fix it. :)
Your best bet would be to abstract your session stuff by creating facade methods, or getters and setters around the session variables rather than access them directly. This way you can return a default value if the one you're after doesn't exist.
I've used array_key_exists() to check if the index is set. If it is not, I display 0 or add store a certain value in that field, else I show the value of that index or add certain value to that field.
Credit to Sven for bringing that up.
to check what u have in your sessions, loop tru it. not sure if this is what u are asking.
foreach($_SESSION as $x=>$y)
{
if(empty($x)) { //do something }
}
When I send over post data I do a print_r($_POST); and I get something like this...
Array ( [gp1] => 9 )
Is there a way to get the "gp1", the name sent over as a value? I tried doing.
echo key($_POST["gp1"]);
But no luck there, I figured it would echo gp1. Is there a way to do this?
you need
print_r(array_keys($_POST));
check this for more details http://php.net/manual/en/function.array-keys.php
You could use foreach to see each key-value pair, or use array_keys to get a list of all keys.
foreach ($_POST as $key => $value) {
// Do whatever
}
Well, if you can write $_POST["gp1"] you already have the key anyway ;)
key() works differently, it takes an array as argument:
The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns NULL.
So if you have not done anything with the array (no traversing), key($_POST) would give you the key of the first element of the array.
Maybe you want a foreach loop?
foreach($_POST as $key => $value) {
}
There are other methods to retrieve keys as to well. It depends on what you want to do.
Please explain what is the meaning of
foreach ($toplist['children'] as $subkey => $subname)
and where the children come from. I'm confused.
Basically $toplist is an array of values. One of those values has been called 'children'.
In this case, the value at position 'children' is itself an array.
Your line of code is telling the computer to loop over each of the values inside the 'children' array and extract the key and value.
$subkey is the key, $subname is the name.
In other words, $toplist['children'][$subkey] == $subvalue
The other elements are coming from the $toplist['children'] array which you got to figure out where it is coming from since you have not put in all the needed code for the question. See this about foreach machenism to learn more about it.
his simply gives an easy way to
iterate over arrays. foreach works
only on arrays, and will issue an
error when you try to use it on a
variable with a different data type or
an uninitialized variable.
php.net