views:

69

answers:

4
private function jsonArray($object)
{
  $json = array();

   if(isset($object) && !empty($object))
   {
      foreach($object as $obj)
      {
        $json[]["name"] = $obj;
      }
   }

   return $json;
}

We are grabbing an object, and if the conditional is met, we iterate over that object. Then... I'm lost on this reading... :s

What's the meaning of the [] here?

$json[]["name"] = $obj;

Thanks in advance, MEM

+4  A: 

$json[] adds an element at the end of the array (numeric index). It's the same as having the following code:

$array=array();
$i=0;
foreach($something as $somethingElse)
{
    $array[]=$somethingElse;
    //is equivalent, in some way, to
    $array[$i++]=$somethingElse;
}
Alexander
Thanks a lot for your time.
MEM
+2  A: 

That's the equivalent to this:

$json[] = array('name' => $obj);
Tatu Ulmanen
That seems much more readable. :)
MEM
+2  A: 

It adds the contents of $obj to a new field in $json and there in the field "name".

Little example:

$arr = array();
$arr[] = "Hello";
$arr[] = "World!";

Then, $arr will contain:

Array (
 0 => "Hello",
 1 => "World!"
)

Or, as in your example with another array in the field:

$arr = array();
$arr[]["text"] = "Hello";
$arr[]["text"] = "World!";

Becomes

Array (
 0 => Array (
  "text" => "Hello"
 ),
 1 => Array (
  "text" => "World!"
 )
)
ApoY2k
With a zero-based index, I presume
Alexander
Of course, my mistake ;)
ApoY2k
Thanks a lot. The fact that $arr[] works like so, is due to php proper way of working?
MEM
+2  A: 

$json[] automatically creates a new element at the end of the array - here is an example:

$json[]["name"] = "object1";
$json[]["name"] = "object2";
$json[]["name"] = "object3";
$json[]["name"] = "object4";

And here is what it displays:

Array
(
    [0] => Array
        (
            [name] => object1
        )

    [1] => Array
        (
            [name] => object2
        )

    [2] => Array
        (
            [name] => object3
        )

    [3] => Array
        (
            [name] => object4
        )

)
xil3
Thanks a lot. The clear presentation of the output have help me understand it as well. (I was unable to var_dump because the php is loaded from an ajax call. :s)
MEM