Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create this array? (PHP)

Tags:

arrays

php

I am a little stuck on how to create this array.

My data:

category_id | category_name
     1              bikes
     2              cars
     3              books
     4              computers

Array:

$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
    $category_id=$row['category_id'];
    $category_name=$row['name'];
}

I want to create an array so that I can echo the data in a radio list like...

<input type='radio' value='<?PHP echo $category['category_id']; ?>' 
name='category[]'><?PHP echo $category['category_name']; ?>

o bikes
o cars
o books
o computers 

The problem is that the array only consists of one pair (1, bikes) and not all the data. How can I make an array with all the data?

Thanks!

like image 678
jpjp Avatar asked Aug 24 '26 11:08

jpjp


1 Answers

You are doing three things wrong, first you are not actually setting $category to equal anything - only the values of two undefined values, which default to null. So you end up with an array like:

array('category_id' => null, 'name' => null)

Second, you are doing nothing with the values of $category_id and $category_name when you do set them. Next, you are not going through the array item by item, you simply output the initial way it was set - which is linked to another problem that your array is short of a dimension. It should be 2-dimensional, not 1-dimensional.

This code sums up the gist of it all. I would suggest reading up on how arrays work in PHP and how to define them, they're a very commonly used data type throughout frameworks and the like.

$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);

$categories=array();

while ($row = $result->fetch_array()){
    $categories[] = array('category_id' => $row['category_id'], 'category_name' => $row['name']);
}

Then when you need to output:

foreach ( $categories as $category ) {
    ?>
    <input type='radio' value='<?php echo $category['category_id']; ?>' name='category[]'><?php echo $category['category_name']; ?>
    <?php
}

This can of course be cleaned up further.

like image 142
Geoff Adams Avatar answered Aug 27 '26 01:08

Geoff Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!