/    Sign up×
Community /Pin to ProfileBookmark

create an array of values from mysqli_fetch_array

From my query, I’m returning two columns from my database being PK_MenuItemCategoryId & CategoryTitle, so far so good
following on from that, doing a print_r, I get the following associative array as a result:

`Array
(
[PK_MenuItemCategoryId] => 1
[CategoryTitle] => Traditional Favourites
)
Array
(
[PK_MenuItemCategoryId] => 2
[CategoryTitle] => Starters
)
Array
(
[PK_MenuItemCategoryId] => 3
[CategoryTitle] => Mains
)`

Even that by my understanding is correct but question1 is should the keys be the same?
Question 2: The result I want is the value from PK_MenuItemCategoryId to be key and value from CategoryTitle to be value

in other words

1 => Traditional Favourites
2 => Starters
3 => Mains

Being a newbie to PHP, I’m struggling to find a solution, I get the feeling it would be along the lines of assigning the associative array to an array but I’m not sure as to assigning the keys and values

any ideas/ solutions would be greatly appreciated

to post a comment
PHP

16 Comments(s)

Copy linkTweet thisAlerts:
@ginerjmApr 14.2019 — Yes - a simple loop over your query results will produce the results you laid out.
<i>
</i>$array = array();
foreach($results as $row)
{
$k = $row['PK_MenuItemCategoryId'];
$v = $row['CategoryTitle'];
$array[$k] = $v;
}


Note: untested.
Copy linkTweet thisAlerts:
@nsathauthorApr 14.2019 — the $result variable you used, is that the variable I would have assigned to mysqli_fetch_assoc

here is the code I with created with you solution embedded but it doesn't work for some reason, could you check this over including the variable name used:
``<i>
</i>$runSql = mysqli_query($connect, $queryCatTitle);
if($runSql) {
if (mysqli_num_rows($runSql) &gt; 0) {
while ($resultsCatTitle = mysqli_fetch_assoc($runSql)) {

$array = array();
foreach($resultsCatTitle as $row)
{
$k = $rowPK_MenuItemCategoryId'];
$v = $row[CategoryTitle'];
$array[$k] = $v;
print_r(array_values($array));
}

}
}
}<i>
</i>
``
Copy linkTweet thisAlerts:
@NogDogApr 14.2019 — There's no need to assign the original keys to new, 1-character keys:
<i>
</i> $array = array();
foreach($resultsCatTitle as $row)
{
$array[$row['PK_MenuItemCategoryId']] = $row['CategoryTitle'];
}
print_r($array);
Copy linkTweet thisAlerts:
@ginerjmApr 14.2019 — Nogdog - from the example the OP posted I thought I was giving him what he wanted.

OP - one does not do a while loop with a foreach loop inside of it. Plus - you don't create the array variable inside of any loop - you do it before the loop as I did.

Stick with your while loop and see if you can make the changes to make it all work. Obviously - drop the foreach.
Copy linkTweet thisAlerts:
@nsathauthorApr 14.2019 — @NogDog#1602783 that does not work, it does not show me anything on the page or even when I go to view-source.

It would been helpful if it showed me some kind of error code or what the error is but out of luck on that
Copy linkTweet thisAlerts:
@NogDogApr 14.2019 — > @nsath#1602791 It would been helpful if it showed me some kind of error code or what the error is but out of luck on that

Maybe you need to output something in cases where either of these conditions are false, and make sure you're even getting to that code:
<i>
</i> if($runSql) {
if (mysqli_num_rows($runSql) &gt; 0) {
//
// code that processes the results
//
}
else {
echo "No rows found."; // or whatever you want here
}
}
else {
throw new Exception("DB error: ".$connect-&gt;error());
}
Copy linkTweet thisAlerts:
@nsathauthorApr 15.2019 — @NogDog#1602794 the line used if (mysqli_num_rows($runSql) &gt; 0) {


does output rows hence the results in the original post
Copy linkTweet thisAlerts:
@nsathauthorApr 15.2019 — @ginerjm#1602776 I don't understand what wrong, everywhere I've looked online mainly stackoverflow, the foreach part makes sense, so does the$k = $row['PK_MenuItemCategoryId'];<br/>
$v = $row['CategoryTitle'];


but assigning the $k as key and $v as value is in my idea where its going wrong

I've even tried $array = array_fill_keys($k, $v) but no avail

its throwing out a HTTP 500 error
Copy linkTweet thisAlerts:
@ginerjmApr 15.2019 — If you have not solved this yet, PLEASE post the code that you have tried to use for the processing of the query results and I will address it. Posting your unhappiness with code does not help you if you don't POST THE CODE.
Copy linkTweet thisAlerts:
@nsathauthorApr 15.2019 — fair enough


$connect = mysqli_connect($hostname, $username, $password);

mysqli_select_db($connect, $database_name);

if ($connect) {
$queryCatTitle = "SELECT PK_MenuItemCategoryId, CategoryTitle FROM lookupTblMenuItem_Category";
$runSql = mysqli_query($connect, $queryCatTitle);
if($runSql) {
if (mysqli_num_rows($runSql) > 0) {
while ($resultsCatTitle = mysqli_fetch_assoc($runSql)) {

$resMainCatgTitleToArr = array();
foreach($resultsCatTitle as $v) {

$ky = $v['lookupTblMenuItem_Category_PK_MenuItemCategoryId'];
$val = $v['lookupTblMenuItem_Category_CategoryTitle'];




}
print_r(array_values($resMainCatgTitleToArr));

}
}
}
} else {
die("Connection could not be established: " . mysqli_connect_error());
}`
Copy linkTweet thisAlerts:
@ginerjmApr 15.2019 — YOu apparently didn't read my previous post telling you to eliminate the foreach loop and stick with the while loop. Do that and show us that NEW code if it still doesn't work.
Copy linkTweet thisAlerts:
@nsathauthorApr 15.2019 — sorry

$connect = mysqli_connect($hostname, $username, $password);<br/>
mysqli_select_db($connect, $database_name);

<i> </i><CODE>if ($connect) {
<i> </i> $queryCatTitle = "SELECT lookupTblMenuItem_Category_PK_MenuItemCategoryId, lookupTblMenuItem_Category_CategoryTitle FROM lookupTblMenuItem_Category";
<i> </i> $runSql = mysqli_query($connect, $queryCatTitle);
<i> </i> if($runSql) {
<i> </i> if (mysqli_num_rows($runSql) &gt; 0) {
<i> </i> while ($resultsCatTitle = mysqli_fetch_assoc($runSql)) {

<i> </i> $resMainCatgTitleToArr = array();
<i> </i>

<i> </i> $ky = $v['PK_MenuItemCategoryId'];
<i> </i> $val = $v['CategoryTitle'];

<i> </i>
<i> </i> $resMainCatgTitleToArr[$ky] = $v;
<i> </i>
<i> </i>
<i> </i> print_r(array_values($resMainCatgTitleToArr));

<i> </i> }
<i> </i> }
<i> </i> }
<i> </i>} else {
<i> </i> die("Connection could not be established: " . mysqli_connect_error());
<i> </i>}
Copy linkTweet thisAlerts:
@ginerjmApr 15.2019 — I see that you really didn't put any effort into your code..... tsk,tsk...

Here is how I would write it:
<i>
</i>if (!$connect)
{
echo "Error making db connection";
exit();
}
// Begin query now. HINT - YOU REALLY NEED TO STOP EMBEDDING
// THE TABLE NAME INTO YOUR COLUMN NAMES. OMG!!!
//
// And using shorter var names will keep you from going crazy
// from all the extra typing/reading/correcting you must be doing!!!
//
$q = "SELECT lookupTblMenuItem_Category_PK_MenuItemCategoryId,
lookupTblMenuItem_Category_CategoryTitle
FROM lookupTblMenuItem_Category";
$qrslts = mysqli_query($connect, $q);
// Did query run ok?
if($qrslts)
{
echo "Query failed to run properly (show error message)";
}
else
{
if (mysqli_num_rows($qrslts) &gt; 0)
{
$arr = array();
while ($row = mysqli_fetch_assoc($runSql))
{
$ky = $row['lookupTblMenuItem_Category_PK_MenuItemCategoryId'];
$val = $row['lookupTblMenuItem_Category_CategoryTitle'];
$arr[$ky] = $v;
}
// WHY DID YOU ASK TO SHOW THE ID VALUES BEFORE NOW IF YOU
// ONLY WANT TO DISPLAY THE TITLES NOW???
print_r(array_values($arr));
}
else
echo "No query results found";
}
exit();

Note my comments throughout.
Copy linkTweet thisAlerts:
@nsathauthorApr 15.2019 — shit a very big sorry it was the browser that was playing up but once I had opened the page in a new tab it loaded up perfectly
Copy linkTweet thisAlerts:
@ginerjmApr 15.2019 — Huh? You telling us that your browser was playing tricks on you?


Nothing you relayed to us indicates that could be possibly the problem you wanted help with.

Good luck in your future endeavors.
Copy linkTweet thisAlerts:
@siddhi_patelMay 10.2019 — try this may be help you :

if (!$connect)

{

echo "Error making db connection";

exit();

}

$q = "SELECT lookupTblMenuItem_Category_PK_MenuItemCategoryId,

lookupTblMenuItem_Category_CategoryTitle

FROM lookupTblMenuItem_Category";

$qrslts = mysqli_query($connect, $q);

// Did query run ok?

if($qrslts)

{

echo "Query failed to run properly (show error message)";

}

else

{

if (mysqli_num_rows($qrslts) > 0)

{

$arr = array();

while ($row = mysqli_fetch_assoc($runSql))

{

$ky = $row['lookupTblMenuItem_Category_PK_MenuItemCategoryId'];

$val = $row['lookupTblMenuItem_Category_CategoryTitle'];

$arr[$ky] = $v;

}

// WHY DID YOU ASK TO SHOW THE ID VALUES BEFORE NOW IF YOU

// ONLY WANT TO DISPLAY THE TITLES NOW???

print_r(array_values($arr));

}

else

echo "No query results found";

}

exit();
×

Success!

Help @nsath spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...