Zaz
Zaz

Reputation: 1102

how to create an array of object in php

I want to clean my old_array and split it up to array of objects. So the new_array contains string and integer.

This is my old_array named $test_temp_variable which is only in string.

discount_org: [
[
"{"day":"00:00"",
""time":"08:00"",
""discount":"10:00""
],
[
""day":"00:00"",
""time":"14:00"",
""discount":"10:00""
]

This is my desired output

discount_org: [
{
day: 0,
time: 8,
discount: 10
},
{
day: 0,
time: 14,
discount: 10
}

but is this even possible in PHP? I have tried in several object-oriented features, but always end up not working. If yes, can you give a finger point?

var dump of my old array

array(7) {
  [0]=>
  array(3) {
    [0]=>
    string(13) "{"day":"8:00""
    [1]=>
    string(14) ""time":"12:00""
    [2]=>
    string(15) ""discount":"10""
  }
  [1]=>
  array(3) {
    [0]=>
    string(12) ""day":"8:00""
    [1]=>
    string(14) ""time":"12:00""
    [2]=>
    string(15) ""discount":"10""
  }

Upvotes: 0

Views: 166

Answers (3)

Expedito
Expedito

Reputation: 7795

You can convert your array to an array of objects using stdClass:

$arr[] = array('day' => 0,
                'time' => 8,
                'discount' => 10);
$arr[] = array('day' => 0,
                'time' => 14,
                'discount' => 10);
$arr[] = array('day' => 1,
                'time' => 9,
                'discount' => 15);
$discount_org = array();
foreach ($arr as $key => $disc){
    $item = new stdClass;
    foreach ($disc as $key2 => $val){
        $item->$key2 = $val;
    }
    $discount_org[] = $item;
}
var_dump($discount_org);

Upvotes: 0

JorgeeFG
JorgeeFG

Reputation: 5961

Maybe:

<?php

class MyClass
{
  public $property1;
  public $property2;
}

$array = array();

$object1 = new MyClass;
$object1->$property1 = 0;
$object1->$property2 = 22;


$object2 = new MyClass;
$object2->$property1 = 11;
$object2->$property2 = 32;

$array[] = $object1; // This adds in order, this would be on $array[0]
$array[] = $object2; // $array[1]

// OR associative way:

$array['Object1'] = $object1;
$array['Object2'] = $object2;

?>

Upvotes: 0

user1648409
user1648409

Reputation:

If i do understand you correctly you have to make an object for each array-index you want to have, like:

class Obj {
    public $Int;
    public $String;

    public function setInt($Int) {
        $this->Int = $Int
    }
    public function setString($String) {
        $this->String= $String
    }
}

then make some objects out of it, like:

$Test = new Obj();
$Test->setInt(3);

and add them to your array like:

$TestArray[] = $Test;

You can now access them like:

$TestArray[0]->Int;

Is that what you mean?

Upvotes: 1

Related Questions