Currently I have something to the effect:
<?php
// ...More Code
$result = mysqli_query($mysqli, "SELECT * FROM stock_types");
if(!$result || mysqli_num_rows($result) < 1) die('error');
$stock_types = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_free_result($result);
die(print_r($stock_types,true));
// More Code...
?>
Will output something to the effect:
Array (
[0] => Array (
[type_id] => 1
[type_name] => In Stock
[type_visible] => 1
[type_locked] => 0
)
[1] => Array (
[type_id] => 2
[type_name] => Out of Stock
[type_visible] => 1
[type_locked] => 1
)
[2] => Array (
[type_id] => 3
[type_name] => Offline
[type_visible] => 0
[type_locked] => 1
)
[3] => Array (
[type_id] => 5
[type_name] => Hidden
[type_visible] => 0
[type_locked] => 0
)
)
Is there a mysqli fetch filter (correct term?) that will use the primary key from the result set if one exists as the array index value? In case my question is not clear it would result in something instead to his effect:
Array (
[1] => Array (
[type_name] => In Stock
[type_visible] => 1
[type_locked] => 0
)
[2] => Array (
[type_name] => Out of Stock
[type_visible] => 1
[type_locked] => 1
)
[3] => Array (
[type_name] => Offline
[type_visible] => 0
[type_locked] => 1
)
[5] => Array (
[type_name] => Hidden
[type_visible] => 0
[type_locked] => 0
)
)
It's not essential for the type_id
values to be removed, but it would be super useful if the Primary Key could be used to index the array. I can do this with a fetch loop but I'm wondering if there is a simpler more elegant way of handling this.
There is no convenient function for this in ext/mysqli. But you can build the array in the manner you want by fetching the rows one by one and putting them into the right array key:
This example assumes the primary key is the first column:
$set = array();
while ($row = $result->fetch_assoc()) {
$set[array_shift($row)] = $row;
}
To do it with fetch_all(), you could process the while dataset fetched:
$set = array();
$data = $result->fetch_all();
while ($row = array_shift($data)) {
$set[array_shift($row)] = $row;
}
this is exactly what I am also looking for, here is what simple example with standard php function.This works only if your array is of length 2.
Array
(
[0] => Array
(
[id] => 1
[name] => xxx
)
[1] => Array
(
[id] => 2
[name] => yyy
)
)
you can make as below format using function: array_column
Array
(
[1] => xxx
[2] => yyy
)
code sample:
$result_set = mysqli_fetch_all($restult_set , MYSQLI_ASSOC);
//syntax: array_column(arg, column_key, index_key)
$result_set = array_column($result_set, 'name' , 'id');
this works great if you have only array of length of two, saves lot of mysqli call against using it as mysqli_fetch in while loop.Hope this may be usefull.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With