PHP - 如何从对象中提取特定键的数据

时间:2016-10-03 15:44:03

标签: php arrays json

我将值存储在format中的数据库中,如:

title = {"en":"test package en","ar":"test package ar"}
description = {"en":"test desc en","ar":"test decription ar"}

当我查询我的数据库时,它会返回如下数组:

    array (size=3)
  0 => 
    object(stdClass)[39]
      public 'id' => string '1' (length=1)
      public 'name' => string '{"en":"test package en","ar":"test package ar"}' (length=47)
      public 'description' => string '{"en":"test desc en","ar":"test decription ar"}' (length=147)
      public 'price' => string '{"en":"200 en","ar":"200 ar"}' (length=29)
      public 'duration' => string '{"en":"1 hr","ar":"1 hr ar"}' (length=28)
      public 'created_at' => string '2016-09-30 01:53:24' (length=19)
      public 'updated_at' => string '2016-09-30 01:53:24' (length=19)
      public 'created_by' => string '1' (length=1)
      public 'updated_by' => string '1' (length=1)

如何将此数组中的值分隔为

array(
  'en'=>array(
    'name'=>'test package en',
    'desc'=>'test desc en',
  )
  'ar'=>array(
    'name'=>'test package ar',
    'desc'=>'test desc ar'
  )
)

1 个答案:

答案 0 :(得分:1)

在我看来,你不应该将JSON存储到你的数据库中(有点失败)。您应该只有另一个字段language并按如下方式存储它:

|       title       | description | language |
| ----------------- | ----------- | -------- |
| test package (ar) |    .....    |    ar    |
| test package (en) |    .....    |    en    |

如果你仍然希望保持这样,你需要创建一个变换器函数(并使用json_decode),如下所示:

function transform($fields)
{
    $transformed = [
        'en' => ['title' => '', 'desc' => ''],
        'ar' => ['title' => '', 'desc' => '']
    ];

    $title_json = json_decode($fields['title'), true);
    $transformed['en']['title'] = $title_json['en'];
    $transformed['ar']['title'] = $title_json['ar'];

    $desc_json = json_decode($fields['desc'), true);
    $transformed['en']['desc'] = $desc_json['en'];
    $transformed['ar']['desc'] = $desc_json['ar'];

    return $transformed;
}