【问题标题】:how to get object value如何获取对象值
【发布时间】:2019-08-08 12:55:30
【问题描述】:

我的会话中有这个对象

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

【问题讨论】:

  • 有什么问题?

标签: php arrays laravel laravel-5


【解决方案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
         ]);
     }
}

我希望它会有所帮助。

【讨论】:

  • 不,不会。 attributes 的每一项都是一个单独的对象。
  • @gulshan ErrorException (E_NOTICE) 试图获取非对象的属性“键”
  • 将json解码成数组后显示输出??
  • @mohammadHosseini 你能把完整的 json 放在这里吗?
  • 错误:json_decode() 期望参数 1 为字符串,给定数组
【解决方案2】:

你用这个:

$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

【讨论】:

  • @mohammadHosseini 您在 5 和 7 的键之前有两次 '。将其转换为 "' 用于字符串声明,您可以在其中使用它们)
【解决方案3】:

这里有一个解决方案。

$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

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2015-11-02
    • 2011-05-14
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多