Page 1 of 1

Arrays Values

Posted: Fri Sep 28, 2007 3:26 am
by phpcoder
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>";
	}
	
	?>

Posted: Fri Sep 28, 2007 3:57 am
by Hemlata
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,

Posted: Fri Sep 28, 2007 8:11 am
by John Cartwright
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