2

I've saved all my data to an array, and I want to get the 'name' of a supplied 'code'.

How to I get the array row of that code?

Also, is this the most efficient process?

 id  |  code  |  name     |  
__________________________
1   |  KNTY  |  Kentucky |
2   |  PURD  |  Purdue   |
3   |  TEXS  |  Texas    |


// Move data to array
$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
   $array[] = $row;
}

// Code I want a name for
$code = "KNTY";
// MYSTERY STEP I NEED HELP WITH
$name = $array[$id]['name'];
0

2 Answers 2

1

I edit with the hint of the comment of itachi. You can use the code as the key of the $array:

$search = "SELECT * FROM table";
$query = mysqli_query($conn, $search);

$array = array();

while($row = mysqli_fetch_assoc($query)) {
   $array[$row['code']] = $row['name'];
}

// Code I want a name for
$code = "KNTY";

$name = $array[$code];
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Adrian - I'll be running this query a lot. I'd prefer not run multiple queries but rather get this information from the array.
Yes, I want to SELECT * from table only once and save to array. Then I want to manipulate the data within the array.
in the loop, use $array[$row['name']][] = $row;
1

Yes you could do something like that, while inside the fetch loop, assign the code as key. This must be unique though:

$search = 'SELECT * FROM table_name';
$query = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($query)) {
    // assign `$row['code']` as key to this rowset
    $array[$row['code']] = $row;
}

$code = 'KNTY';
if(isset($array[$code])) { // add some checking, you wouldn't want undefined index errors
    $name = $array[$code]['name'];
    echo $name;
} else {
    echo 'Sorry not found';
}

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.