Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Find value in object

I have a result of an SQL query that looks like this

Array
(
[0] => stdClass Object
    (
        [field_number] => 1
        [value] => Joe
    )

[1] => stdClass Object
    (
        [field_number] => 2
        [value] => Bloggs
    )

[2] => stdClass Object
    (
        [field_number] => 3
        [value] => 12566
    )

[3] => stdClass Object
    (
        [field_number] => 4
        [value] => 2000-07-24
    )
)

It wont always return all the fields as some are not required therefore not saved to the database.

I know that first name is stored with field number 1. How can I look this up in the object.

EG

 $first_name = $result => field_number == 1

I know thats not right, but Im sure there must be a simple way to get this info?

Thanks

like image 338
MonstaMash Avatar asked May 14 '26 03:05

MonstaMash


1 Answers

If the values in the array are not in order (eg array[0] does not always contain field_number 1) then you will need to iterate the array:

foreach($array as $item){
    if($item->field_number==1){
      $first_name = $item->value;
      break;
    }
}

However, if this is the result of an SQL query, probably you need to rewrite the query to give you data in a more useable form

like image 197
Steve Avatar answered May 15 '26 16:05

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!