kraven2g
kraven2g

Reputation: 167

I can't convert Json to string [OctoberCms]

I'm trying to get the value from an input, that input allows the user to create as many fields as he wants this is how I have created that field in my fields.yaml:

str_og_fb_admins:
        label: Facebook admins
        comment: Insert here the admins names
        span: left
        tab: Facebook
        type: repeater
        form:
          fields:
            str_og_fb_admins:
              label: Facebook admins
              type: text

then on my component I'm calling it this way:

$settings = Settings::instance();
$this->ogFbAdmins = $settings->str_og_fb_admins;

but now I want to get the single values from each singular input and I don't know how, I have tried to use the json_decode(); function but it returns an error.

If I use echo json_encode($this->ogFbAdmins); it returns

{"1":{"str_og_fb_admins":"admin1"},"2":{"str_og_fb_admins":"admin2"}}

but I want to make it return like this:

admin1
admin2

How do I make it to return in the second way?

ps: the error that returns when I use json_decode($this->ogFbadmins); is like this:

"json_decode() expects parameter 1 to be string, array given"

Upvotes: 2

Views: 999

Answers (2)

Sofiene Djebali
Sofiene Djebali

Reputation: 4508

This should work:

PHP

$ogFbAdmins = json_decode(json_encode($this->ogFbAdmins), true);
foreach($ogFbAdmins as $key => $value) {
  echo $value['str_og_fb_admins'] . "\n";
}  

EVAL.IN

Upvotes: 2

RiggsFolly
RiggsFolly

Reputation: 94682

I think $this->ogFbAdmins is an array so you dont need any JSON conversion at all.

Try treating it like an array in Pure PHP

$settings = Settings::instance();
$this->ogFbAdmins = $settings->str_og_fb_admins;
foreach ($this->ogFbAdmins as $adm) {
    echo $adm['str_og_fb_admins'];
}

Now the inner structure may be an object so you may need to do

$settings = Settings::instance();
$this->ogFbAdmins = $settings->str_og_fb_admins;
foreach ($this->ogFbAdmins as $adm) {
    echo $adm->str_og_fb_admins;
}

Upvotes: 3

Related Questions