0
$result=mysql_query("SELECT * FROM users where id=1");
print_r($result);

Here is the result data from mysql query.

Array
(
    [0] => stdClass Object
        (
            [firstname] => "John"
            [middleinitial] => "A."
            [lastname] => "Doe"
        )
)

I want to add address: "USA" after the lastname that will result like this:

Array
(
    [0] => stdClass Object
        (
            [firstname] => "John"
            [middleinitial] => "A."
            [lastname] => "Doe"
            [address] => "USA"
        )
)

How can I append that to $result variable in php? Help would much appreciated. Tnx :)

4
  • 1
    try with $result[0]->address = 'USA'; Commented Feb 18, 2017 at 16:16
  • 1
    Or SELECT *,'USA' as address FROM users where id=1 Then it will be in the array without needing to add it Commented Feb 18, 2017 at 16:18
  • Or better still amend the table to have a column to hold that data Commented Feb 18, 2017 at 16:18
  • tnx @AlfredoEM. It works Commented Feb 19, 2017 at 0:57

3 Answers 3

2

This will work in one/more than one element case

$result = array_map(function ($v) {
    $v->address = "USA";
    return $v;
}, $result);

Give it a try. This should work.

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

Comments

1

This will work

  $result[0]->address = "USA";

Comments

1

You simply need to add a property to the object contained in the first index of your array,

$result[0]->address = 'USA';

Furthermore, if your array has multiple indices and you want to iterate through them all and add an address then you can do the following:

foreach ($result as &$row) {
    $row->address = 'USA';
}

where the & is to pass the $row variable into the loop by reference so that you can modify it.

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.