0

Okay I need to ask

I'm building arrays in this way:

$qe = mysql_query("SELECT * FROM table");
while ($k = mysql_fetch_object($qe)) {
    $array1[] = $k;
}

and I want to add a manual key and value to $array1

I've tried $array1[]['admin']

and $array1['admin'][]

and array_push($array1['admin']=1)

and array_push($array1, 'admin' => 1)

and array_push($array1[], 'admin' => 1)

admin key is always going out of builded array

3 Answers 3

2

Just set a key to a value:

$array1['admin'] = 1;

Or:

$array1[] = $k + array('admin' => 1);
Sign up to request clarification or add additional context in comments.

4 Comments

i tried this too. when i do like this it puts admin key outside of the arrays that builded with mysql before
Then you want to add the key to the $k arrays, not the $array1. See update.
oh god. you got that. i spend almost three hours on this and you did the trick in seconds $array1[] = $k + array('admin' => 1); this gave me errors: Object of class stdClass could not be converted to int and Unsupported operand types but i changed to $array1[] = (array)$k + array('admin' => 1); fixed it. thank you so so so much!
@AliDemirci You are casting $k which is a object to array. If you want array, just use mysql_fetch_assoc but not mysql_fetch_object.
2

You are using mysql_fetch_object which returns object not array.

So you should do:

$k->admin = 1;
$array1[] = $k;

3 Comments

this explains everything. this works too. i marked other answer as accepted just before your answer. but could i ask, which solution is better for performance?
@Ali Don't worry about performance at this level. It'll make no difference you could detect without obsessive profiling. Rather, use what you think makes more sense. If you want to use objects, use objects. Otherwise, use arrays.
@AliDemirci Usually array is fast than object, but not so much, which to use is depending on your needs.
1

You'll need to do the following if you intend on constructing your arrays in this manner.

$qe = mysql_query("SELECT * FROM table");
while ($k = mysql_fetch_object($qe)) {
    $array1[] = Array("admin" => $k);
}

4 Comments

Sorry I forgot to mention. I also tried $array1[] = array($k, 'admin' => 1); it's not what I want. I want to push admin key into the mysql block
Could you provide an example of the array structure you're expecting?
Also are you possibly looking for mysql_fetch_assoc or mysql_fetch_row in place of mysql_fetch_object?
thank you guys deceze's answer is what i've been looking for. i'll up vote for taking your time:)

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.