как получить значение объекта - PullRequest
0 голосов
/ 18 марта 2019

У меня есть этот объект в моем сеансе

name: "test",
is_feature: "0",
attributes: [
  {
   '5': "blue"
  },
  {
   '7': "iOS"
  }
],
cost: "2000",

Я хочу использовать атрибуты в foreach.some, как показано ниже:

foreach ($product->attributes as $attribute){     
   ProductAttributeValue::create([
            'attribute_id' => $attribute->key,  //like 5,7
            'value' => $attribute->value  //like blue,iOS
        ]);
    }

Ответы [ 3 ]

1 голос
/ 18 марта 2019

Вы используете это:

$str = '{"name": "test", "is_feature": "0", "attributes": [{"5": "blue"},{"7": "iOS"}],"cost": "2000"}';
$arr = json_decode($str, true); // convert the string to associative array

foreach($arr["attributes"] as $attribute) {
    $key = key($attribute); // get the first key as "5" of "7"
    echo "key: $key and val: " . $attribute[$key]; // access the value as $attribute[$key] will give blue or ios
};

Живой пример: 3v4l

Ссылка: ключ

1 голос
/ 18 марта 2019

Попробуйте этот цикл :

Сначала вы конвертируете json в ассоциативные массивы, такие как:

$productAttributes = json_decode($product->attributes, true);

, а затем

foreach ($productAttributes as $attributes) {
     foreach ($attributes as $key => $attribute) {
         ProductAttributeValue::create([
             'attribute_id' => $key,  // like 5,7
             'value' => $attribute  // like blue,iOS
         ]);
     }
}

Надеюсь, это поможет.

0 голосов
/ 18 марта 2019

Вот решение для вас.

$strArr = [
    'name'=>"test",
     'is_feature'=> "0",
     'attributes'=>[[5=> "blue"],[7=> "iOS"]],
     'cost'=> "2000"
];
$str = json_encode($strArr);
$arr = (array) json_decode($str);
$att = (array) $arr['attributes'];
foreach($att as  $val) {
    foreach($val as  $key=>$attributes) {
    echo "key: ".$key." and val: " . $attributes . PHP_EOL;
    }
};

Выход:

key: 5 and val: blue
key: 7 and val: iOS

Надеюсь, это поможет вам

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...