2

I would like to know if there is a built in php function for what I'm trying to do here. I'm pulling ids from a mysql db, and this is the result I'm getting.

print_r($result);

// output
Array
(
    [0] => SubCategory Object
        (
          [id] => 1
        )
    [1] => SubCategory Object
        (
          [id] => 5
        )

This is fine... pretty standard (using the Yii framework).

What I need to do is build an array of the ids. Should look like this

print_r($someArray);

// output
Array
(
    [0] => 1
    [1] => 5
    [2] => 14
    [3] => 2

So is there a function built in to do this? Or do I have to loop through it like this?

foreach ($result as $row) {
    // append to new array here
}

Thanks in advance...

2 Answers 2

2

The best way is to use array_map, which returns a new array by applying a transformation function to each element in the starting array. So do something like:

$idsArray = array_map(function($value) { return $value->id; }, $arrWithSubCategoryObjects); 

Note that the above will work in php 5.3 and up, which supports "anonymous" functions. For earlier versions, use:

function mapFunction($value) { return $value->id; };
$idsArray = array_map("mapFunction", $arrWithSubCategoryObjects);

See array_map for more info.

Sign up to request clarification or add additional context in comments.

Comments

0

If you are using YII to pull ids from mysql db, then you can use below code , because it will return result as you desire , then not need to process or convert it further.

$sql="SELECT id FROM TableName";
$result=YII::app()->db->createCommand("$sql")->queryColumn();

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.