【问题标题】:Laravel PHP get value in arrayLaravel PHP在数组中获取值
【发布时间】:2021-03-05 11:32:25
【问题描述】:

我有一个名为“images”的数组

array:6 [▼
  0 => {#371 ▼
    +"id": 15175604535432
    +"product_id": 4673356234888
    +"position": 1
    +"created_at": "2020-03-10T16:52:33-04:00"
    +"updated_at": "2020-03-10T16:52:33-04:00"
    +"alt": null
    +"width": 800
    +"height": 800
    +"src": "https://cdn.shopify.com/s/files/1/0335/4175/0920/products/product-image-1294465746.jpg?v=1583873553"
    +"variant_ids": []
    +"admin_graphql_api_id": "gid://shopify/ProductImage/15175604535432"
  }
  1 => {#372 ▶}
  2 => {#373 ▶}
  3 => {#374 ▶}
  4 => {#375 ▶}
  5 => {#376 ▶}

我知道我需要 'id' 值为 15175604535432 的图像 src。

如果我知道 ID 的值,有没有办法获取 src?

我已经尝试过dd($products[1]->images['id'][15175604535432]->src);$products[1]->images->where('id',15175604535432)->src 但都没有工作

【问题讨论】:

  • 显示您收到的错误。
  • 错误:未定义的索引:id 并调用数组上的成员函数 where() 以获取第二个代码

标签: php arrays laravel laravel-blade


【解决方案1】:
  1. 您知道图像的索引是什么,并且您想检索它的 src:
$images[1]->src // gives src of image in given index
  1. 您可以遍历每个索引:
$id =  "15175604535432";
$imageSrc = null;

foreach( $images as $image ) {
    if( $image->id == $id ) {
        $imageSrc = $image->src; 
        break;
    }
}

if( $imageSrc != null ) {
    // src found
}

你也可以做一个集合,但你只需要一个值。

因此,对于集合,您可以使用“->first()”遍历数组,直到找到第一个匹配值。

最后,您创建一个新对象仅用于检索一个值。

这比 foreach 循环多几个步骤,因此它更广泛。

但它看起来确实“更漂亮”。

【讨论】:

    【解决方案2】:

    如果您愿意,可以使用该数组创建一个 Collection 并使用 Collection 方法来查找您的记录:

    $image = collect($products[1]->images)->where('id', $id)->first();
    
    $src = $image ? $image->src : null;
    

    【讨论】:

    • 你能告诉我你的解决方案比这更快还是更节省内存: images as $obj ) { if( $obj->id == $v ->image_id ) { // 做你的事 $image = $obj->src; // src attr.与 id attr 处于同一级别。休息; } } ?> ....
    • 我的意思是 collect() 是否比使用每个循环来查找元素更好?
    【解决方案3】:

    你可以这样做:

    $image_src = "";
    
    foreach($images as $image) {
    
        if($image->id == "15175604535432") {
         
            $image_src .= $image->src;
    
        }
    
    }
    
    dd($image_src);exit;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 2016-06-06
      • 2021-05-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-19
      • 2021-05-21
      相关资源
      最近更新 更多