douzhang2092 2016-10-03 15:44
浏览 232

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

I am storing the values in my db in format like:

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

When I query my db, it returns me the array like:

    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)

How can I get the values in this array separated like

array(
  'en'=>array(
    'name'=>'test package en',
    'desc'=>'test desc en',
  )
  'ar'=>array(
    'name'=>'test package ar',
    'desc'=>'test desc ar'
  )
)
  • 写回答

1条回答 默认 最新

  • dqs13465424392 2016-10-03 16:00
    关注

    In my opinion, you shouldn't store JSON into your database (kinda defeats the point). You should simply have another field language and store it as follows:

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

    If you still want to keep it like this, you will need to create a transformer function (and use json_decode), such as the following:

    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;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题