skip to Main Content

I have this array called "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 ▶}

and I know that I need src of images where ‘id’ has value 15175604535432.

Is there a way to get src if I know value of ID?

I already try dd($products[1]->images['id'][15175604535432]->src);
and $products[1]->images->where('id',15175604535432)->src but both didnt work

3

Answers


    1. You know in what index of the image is and you want to retrieve its src:
    $images[1]->src // gives src of image in given index
    
    1. You can loop through every index:
    $id =  "15175604535432";
    $imageSrc = null;
    
    foreach( $images as $image ) {
        if( $image->id == $id ) {
            $imageSrc = $image->src; 
            break;
        }
    }
    
    if( $imageSrc != null ) {
        // src found
    }
    

    You can also make an collection, but you only need one value.

    So with collection you iterate over the array with “->first()” until you find the first matching value.

    Finally you create a new object only for retrieving one value.

    This are a few more steps then a foreach loop thus it is more expansive.

    But it does looks “prettier”.

    Login or Signup to reply.
  1. You can make a Collection with that array and use the Collection methods to find your record, if you wanted to:

    $image = collect($products[1]->images)->where('id', $id)->first();
    
    $src = $image ? $image->src : null;
    
    Login or Signup to reply.
  2. You can do:

    $image_src = "";
    
    foreach($images as $image) {
    
        if($image->id == "15175604535432") {
         
            $image_src .= $image->src;
    
        }
    
    }
    
    dd($image_src);exit;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search