如何获得客体价值

时间:2019-03-18 07:41:39

标签: php arrays laravel laravel-5

我的会话中有这个对象

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

我想在foreach中使用属性。类似于下面的代码:

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

3 个答案:

答案 0 :(得分:1)

尝试此循环

首先,您将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
         ]);
     }
}

我希望这会有所帮助。

答案 1 :(得分:1)

您使用此:

$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

参考:key

答案 2 :(得分:0)

这是为您提供的解决方案。

$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

希望这对您有帮助