繁体   English   中英

如何在php中创建对象数组

[英]how to create an array of object in php

我想清理old_array并将其拆分为对象数组。 因此,new_array包含字符串和整数。

这是我的old_array,名为$ test_temp_variable,仅在字符串中。

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

这是我想要的输出

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

但这在PHP中甚至可能吗? 我尝试了几种面向对象的功能,但始终无法正常工作。 如果是,您能指责一下吗?

我的旧阵列的var dump

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""
  }

如果我确实理解正确,则必须为每个要拥有的数组索引创建一个对象,例如:

class Obj {
    public $Int;
    public $String;

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

然后从中制作一些对象,例如:

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

并将它们添加到您的数组中,如下所示:

$TestArray[] = $Test;

您现在可以像这样访问它们:

$TestArray[0]->Int;

你是这个意思吗?

也许:

<?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;

?>

您可以使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM