php implode two tags into one array

440

I want to have one array from these two tags so I can reference it through my client using either tag from the index

$query = "SELECT username,imgDefault from users"
$result = $sql->query($query);
$rows = array();
while($row = $result->fetch_assoc()) {               
            $rows[]=$row;
        }
        $result->close();
        $sql->close();
$str = implode(',', array_map(function($el){ return $el['username']; }, $rows));
$str1 = implode(',', array_map(function($el){ return $el['imgDefault']; }, $rows));

Desired Output Array

username:"d" imgDefault: "a", username:"b" imgDefault: "q",  etc....

Im open to any other output that would help me identify the column value on an index

370

Answer

Solution:

If I understood correctly what you're trying to do is to have the possibility to get a "username" based on a "imgDefault" OR to get a "imgDefault" based on a "username".

You should first get an associative array where the key is the username, and the value is the imgDefault: $query = "SELECT username,imgDefault from users" $result = $sql->query($query);

$associativeArray = array();
while($row = $result->fetch_assoc()) {               
    $currUsername = $row["username"];
    $currImgDefault = $row["imgDefault"];
    $associativeArray[$currUsername]= $currImgDefault;
}
$result->close();
$sql->close();
// $array will look like array("d" => "a", "b" => "q", ...);

Then you can look for a "imgDefault" based on a "username" using:

if (array_key_exists($theUsername, $associativeArray))
{
    $theImgDefault = $associativeArray[$theUsername];
}

And you can look for a "username" based on a "imgDefault" using:

$theUsername = array_search($theImgDefault,$associativeArray);

People are also looking for solutions to the problem: php - Force redirect a URL in WORDPRESS on mobile

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.