PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
phpcoder
Forum Contributor
Posts: 158 Joined: Sat Nov 02, 2002 1:18 pm
Location: Manchester, UK
Post
by phpcoder » Fri Sep 28, 2007 3:26 am
HI,
I cant acces values of arrays. Anything wrong with my code.
Code: Select all
<?php
class ordClass
{
public $Item;
}
$obj = new ordClass;
$obj->Item[]= array ( 'Sku' => "Test1", 'Description' => "Test1");
for ($i=0; $i < count($obj->Item); $i++)
{
print "SKU".$obj->Item[Sku];
print "<br>";
}
?>
Hemlata
Forum Commoner
Posts: 35 Joined: Mon Sep 10, 2007 5:40 am
Location: India
Contact:
Post
by Hemlata » Fri Sep 28, 2007 3:57 am
Hello,
I think you are using wrong way for assigning values to variable '$obj->Item'.
If you modify your code to as follows, you will be getting array values.
Code: Select all
<?php
class ordClass
{
public $Item;
}
$obj = new ordClass;
$obj->Item= array ( 'Sku' => "Test1", 'Description' => "Test1");
for ($i=0; $i < count($obj->Item); $i++)
{
print "SKU".$obj->Item[Sku];
print "<br>";
}
?>
Hope this might solve your issue.
Regards,
John Cartwright
Site Admin
Posts: 11470 Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:
Post
by John Cartwright » Fri Sep 28, 2007 8:11 am
Without going into details about some other issues I see with your script, heres my suggestions
$this->Item is set to public, I would probably make this a private property and create a method to set and retrieve your orders list
count() within a loop is not efficient, storing the count() in a variable and using the variable in the loop is better
As suggested earlier, $obj->Item should store an array of arrays, not simply a single dimensional arrays.
You are still not accessing the properties correctly. Using a for() loop, you should access the indice you are currently looping:
Code: Select all
print "SKU". $obj->Item[$i]['Sku'];
I would probably use a foreach() anyway, and rid myself of the count() call all together
Code: Select all
foreach ($obj->Item as $item)
{
echo $item['Sku'] .'<br>';
}
Always quote your array indices, $item[Sku] will fire a php notice