2

I have a array structured like so

array:2 [▼
  "id_1553623907416" => array:2 [▼
    "id_title" => "About"
    "id_content" => """
      <!DOCTYPE html>
      <html>
      <head>
      </head>
      <body>
      <p>Helllo world</p>
      </body>
      </html>
      """
  ]
  "id_1553623916174" => array:2 [▼
    "id_title" => "Education"
    "id_content" => """
      <!DOCTYPE html>
      <html>
      <head>
      </head>
      <body>
      <p>hello data</p>
      </body>
      </html>
      """
  ]
]

i need to be able to remove the array named id_1553623907416 if it contains the value About in the sub-array key id_title. The ids are dynamic so this has to be dynamically.

that array is stored in the variable @output.

 @foreach ($output as $item)    
   @if($item["id_title"] == "About")
      //remove array 
   @else
     //do something else 
   @endif
@endforeach
2
  • 1
    You could convert your array to a Collection and use the filter() function: laravel.com/docs/5.8/collections#method-filter. If that's too much overhead, use the unset() method in the answer below. Commented Mar 26, 2019 at 18:29
  • I don't think that is a good approach. Seem you are in blade template? If so - that is bad practice to transform data when you are in View of MVC. The only thing you can apply in view is just skip this item and go for next one. Commented Mar 26, 2019 at 20:28

1 Answer 1

3

Using your existing code (I don't know Laravel) just expose the key in the foreach and unset:

 @foreach ($output as $key => $item)    
   @if($item["id_title"] == "About")
      unset($output[$key]); 
   @endif
@endforeach

If there can be only one then add break; after the unset.

Or you can filter them out:

$output = array_filter($output, function($v) { return $v['id_title'] != 'About'; });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.