Welcome Guest, Not a member yet? Register   Sign In
How to create an array of objects??
#1

[eluser]umbongo[/eluser]
How can i create an array of objects?

I am trying to get a result like..

Array ( [0] => stdClass Object ( [id] => 123 [name] => Name [color] => red... ) [1] => stdClass Object ( [id] => 124 ...

the following has not been working
Code:
$i=0;

foreach($hits as $hit){
   $results[$i]->id= $hit->id;
   $results[$i]->name=$hit->name;
   $results[$i]->color=$hit->color;

   $i++;
}

Sorry for the noob question i'm not to hot on objects etc.
#2

[eluser]mglinski[/eluser]
You need to use a special class to create a "blank" object in php. Here is a quick example.
Code:
<?php

$array = array();
$data = new stdClass();

$data->id = 'id';
$data->name = 'name';
$data->color = 'color';

$array[] = $data;
$array[] = $data;
$array[] = $data;

print_r($array);
/*
Array
(
    [0] => stdClass Object
        (
            [id] => id
            [name] => name
            [color] => color
        )

    [1] => stdClass Object
        (
            [id] => id
            [name] => name
            [color] => color
        )

    [2] => stdClass Object
        (
            [id] => id
            [name] => name
            [color] => color
        )

)
*/

-Matt
#3

[eluser]gwelter[/eluser]
Code:
class myc
{
    var $i='dude';
    function pr(){echo 'hi '.$this->i.'<br>';}
}

$test = new myc;
$test->i='compadre';
$testtwo = new myc;
$testtwo->i = 'senor';

$arr = array($test, $testtwo);

$arr[0]->pr();
$arr[1]->pr();

foreach($arr AS $cl) { $cl->pr(); }

Output:

hi compadre
hi senor
hi compadre
hi senor

Works for me..?
#4

[eluser]gwelter[/eluser]
Code:
class myc
{
    var $i='dude';
    function pr(){echo 'hi '.$this->i.'<br>';}
}

$test = new myc;
$test->i='compadre';
$testtwo = new myc;
$testtwo->i = 'senor';

$arr = array($test, $testtwo);

$arr[0]->pr();
$arr[1]->pr();

$arr[0]->i='bob';
$arr[1]->i='mike';

foreach($arr AS $cl) { $cl->pr(); }

Output:

hi compadre
hi senor
hi bob
hi mike

Setting works too..
#5

[eluser]Mr-H[/eluser]
if you ran this code from database you can use :

$this->db->where('id',$id);
$query = $this->db->get('mydatabase');
return $query->result();

$query->result() return an array of object from database




Theme © iAndrew 2016 - Forum software by © MyBB