0

I am trying to create an array which will follow something like this

array(
    [Matt => 3],
    [Tom => 7]),
    //etc
)

I want this set up so I can use it with a mysql_fetch_assoc() such as

    $i=0;
    while($data = mysql_fetch_assoc($query)){

        $Array[$i] = $data['name'];  // sore name as part of array
        $Array[$i][0] = ($data['number']; // keep number with the name.
        $i++;

    }

This does not work . I was unable to do so with a array_push. Can someone please guide me? Is my array declaration wrong or even important?

2 Answers 2

2
while($data = mysql_fetch_assoc($query)){
    $Array[$data['name']] = $data['number']; // keep number with the name.
}

that assumes no duplicate names - which might not be the intention and I've misread your question...

alternatively

while($data = mysql_fetch_assoc($query)){
    $Array[] = array($data['name'] => $data['number']); // keep number with the name.
}

The latter is something that you can do with pdo fetchAll(PDO::FETCH_ASSOC); see here

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

6 Comments

PDOStatement::fetchAll() won't produce an associative array like that but I think your second example is probably what the OP wants. +1
@Phil PDO will if you use the PDO::FETCH_ASSOC const. on fetchAll you will get a numerically indexed array of tuples which contains an associative array of the fields and their values.
Yes, but it won't give you Matt => 3. It will give you name => Matt, number => 3
yeah - think that oversight means bed-time :P BUT easier to work with in most cases...
make sure you accept the answer mattyd. it helps your reputation when asking future questions.
|
0

I can't quite tell exactly what you want but does this help?

$array = array();
while ($data = mysql_fetch_assoc($query)) {
    $array[$data['name']] = $data['number'];
}

This will produce an array like the following (print_r style)

Array
(
    [Matt] => 3,
    [Tom]  => 7
)

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.