0

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

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

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 转储

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

3 回答 3

1

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

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;

你是这个意思吗?

于 2013-07-18T13:47:51.393 回答
0

也许:

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

?>
于 2013-07-18T13:48:17.527 回答
0

您可以使用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);
于 2013-07-18T15:46:41.330 回答