0

I get some random PHP arrays generated by a backend, and I want to loop in it, and ignore all entries where weight > 5000. Some array example:

array(4) {
  [0]=>
  object(stdClass)#72 (3) {
    ["weight"]=>
    string(2) "80"
    ["added_date"]=>
    string(19) "2016-10-02 11:49:27"
    ["etid"]=>
    string(1) "3"
  }
  [1]=>
  object(stdClass)#68 (3) {
    ["weight"]=>
    string(4) "6760"
    ["added_date"]=>
    string(19) "2016-10-04 14:30:25"
    ["etid"]=>
    string(1) "3"
  }
  [2]=>
  object(stdClass)#63 (3) {
    ["weight"]=>
    string(4) "1360"
    ["added_date"]=>
    string(19) "2016-10-04 14:56:21"
    ["etid"]=>
    string(1) "3"
  }
  [3]=>
  object(stdClass)#122 (3) {
    ["weight"]=>
    string(4) "1040"
    ["added_date"]=>
    string(19) "2016-10-25 16:52:25"
    ["etid"]=>
    string(1) "3"
  }

And my desired output will be:

array(1) {
  [0]=>
  object(stdClass)#72 (3) {
    ["weight"]=>
    string(2) "6760"
    ["added_date"]=>
    string(19) "2016-10-02 11:49:27"
    ["etid"]=>
    string(1) "3"
  }

How will look a PHP for loop to only filter the array values with weight >5000. Thank you.

3
  • Did you try something? Commented Dec 9, 2016 at 15:52
  • Sounds pretty straight forward. What is your question? Commented Dec 9, 2016 at 15:54
  • Try this php.net/manual/ru/class.filteriterator.php Commented Dec 9, 2016 at 15:54

2 Answers 2

2

Many approaches exist, but this is probably the most simple and straight forward:

<?php
$outputArray = [];
foreach ($inputArray as $inputElement) {
  if (5000 <= (int)$inputElement->weight) {
    $outputArray[] = $inputElement;
  }
}
var_dump($outputArray);
Sign up to request clarification or add additional context in comments.

3 Comments

@JeanDoux The logic was the wrong way 'round: the OP wants entries below 5000. So an elemtnshould be accepted in the output array if its weight is below 5000.
the Op wants above 5000, look at his example.
@JeanDoux Thanks for pointing that out. I could have sworn it was the other way 'round... my bad. Thanks!
0

You can use array_filter fonction :

function BigWeight($value)
{
    return (is_object($value) && $value->weight >= 5000);
}

 $filtered_array = array_filter($your_array, "BigWeight");
 print_r($filtered_array);

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.