baig772
baig772

Reputation: 3488

PHP - How to extract data for specific key from object

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'
  )
)

Upvotes: 0

Views: 60

Answers (1)

user2463
user2463

Reputation: 752

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

Upvotes: 1

Related Questions