1

I am trying to assign my db returned results to an array

I have

$results = Db::get('get_items', array('id' =>$id));

$Info['items'][1]['title'] = $results[0]['Name'];
$Info['items'][1]['name'] = $results[0]['Filename'];
$Info['items'][1]['type'] = $results[0]['Type];

The DB only returns 1 row of data.

I need my $info looks like the following

Array
(
    [items] => Array
        (
            [1] => Array
                (
                    [title] => Title test
                    [filename] => test.xml
                    [type] => company
                )

        )

    [mis] => data
)

I was wondering if there are a better way to assign the value to $info than just hardcoded them all. Thanks a lot!

2
  • have you tried print_r($results); ? what did you get? Commented Jun 7, 2013 at 0:21
  • I did get what I need as an output, but I want to see if I can make the codes prettier. Commented Jun 7, 2013 at 0:22

2 Answers 2

5

Use an array to describe the key mappings:

$map = array('Name' => 'title',
             'Filename' => 'name',
             'Type' => 'type');

foreach ($results[0] as $key => $value) {
    $Info['items'][1][$map[$key]] = $value;
}

Any time you want to perform some kind of one-to-one translation, you should immediately think of using an associative array.

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

Comments

0

Change your query so you are getting the fields AS the field name you want. I don't know what your DB class does, but with mySQL you can do

SELECT `Filename` as `name` FROM table;

Then you can do:

$Info['items'][1] = $results[0];

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.