2

I have an array of objects as follows:

[0] => stdClass Object
    (
        [lid] => 2492
        [post_title] => Winter League 2012/2013
        [eid] => 2121
        [etitle] => a 2013
        [rid] => 2358
        [rtitle] => sdcc2013_2M_W
        [rtype] => W
    )

[1] => stdClass Object
    (
        [lid] => 2492
        [post_title] => Winter League 2012/2013
        [eid] => 2121
        [etitle] => a 2013
        [rid] => 2359
        [rtitle] => sdcc2013_4M_M
        [rtype] => M
    )

[2] => stdClass Object
    (
        [lid] => 2492
        [post_title] => Winter League 2012/2013
        [eid] => 2123
        [etitle] => e 2013
        [rid] => 2360
        [rtitle] => eircom_Women_2.5Mile
        [rtype] => W
    )

[3] => stdClass Object
    (
        [lid] => 2492
        [post_title] => Winter League 2012/2013
        [eid] => 2123
        [etitle] => e 2013
        [rid] => 2362
        [rtitle] => eircom2013_men_5mile
        [rtype] => M
    )

and i want to 'get' the subset of 'rid' values

 (2358,2359,1360,2362)

which of array manipulation functions should i use?

0

2 Answers 2

4

I would suggest array_map().

$original_array; // your original array
$rid_array = array_map(function($val) {
    return $val->rid;
}, $original_array);

Or for PHP < 5.3

$original_array; // your original array
$rid_array = array_map('map_function', $original_array);

function map_function($val) {
    return $val->rid;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I believe he's looking to set them. Not get them.
I kind of took it as a typo in imprecise language issue, as the values shown are the same as those currently in the array of objects. So read it to mean, he wanted to set an array with the values rid values from the array of objects.
Is the callback function supported in PHP version 5.2.17?
@emeraldjava You need to be on PHP 5.3 or greater to utilize closures (anonymous functions) as shown. See updated answer for compatibility with older versions of PHP.
1

I would use array_map() with a callback function that sets the rid field of the object.

function set_rid($obj, $val)
{
    return $obj->rid = $val;
}

$my_rids = array(
    '1',
    '2',
    '3',
    '4'
);
array_map('set_rid', $my_array, $my_rids);

1 Comment

thanks - how to 'set' the values was going to be the next question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.