0

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'
  )
)
2
  • 1
    Use php's json_decode() with the second parameter set to true to decode json into associative arrays. Commented Oct 3, 2016 at 15:50
  • It is json. Use json_decode to extract the data. Commented Oct 3, 2016 at 16:27

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.