Laravel PHP 获取数组中的值

Laravel PHP get value in array

我有一个名为“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 ▶}

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

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

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

  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
}

你也可以制作一个collection,但你只需要一个值。

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

最后您创建了一个新的 object 仅用于检索一个值。

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

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

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

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

$src = $image ? $image->src : null;

你可以这样做:

$image_src = "";

foreach($images as $image) {

    if($image->id == "15175604535432") {
     
        $image_src .= $image->src;

    }

}

dd($image_src);exit;