Array Data show not work - php

After querying my data from database I have this type of array in $rown
Array
(
[0] => 60
[id] => 60
[1] => 78
[cholest] => 78
[2] => 2014-07-13
[Cdate] => 2014-07-13
)
Array
(
[0] => 61
[id] => 61
[1] => 0
[cholest] => 0
[2] => 2014-07-15
[Cdate] => 2014-07-15
)
My code
$resultn = mysql_query($sqln);
if(mysql_affected_rows() > 0)
{
while($rown = mysql_fetch_array($resultn))
{
$result_finalb = $rown["id"];
}
}
when I print $result_finalb then show only second array data, but I want to show both array data.

You are setting a single variable $result_finalb with a value.
If you want to create an array of values, using $result_finalb[] will create an array item with the value you assign.
The first time will be $result_finalb[0], second will be $result_finalb[1], and so on through however many iterations you go through.

You are missing square brackets. Use this:
$resultn = mysql_query($sqln);
if(mysql_affected_rows() > 0)
{
while($rown = mysql_fetch_array($resultn))
{
$result_finalb[] = $rown["id"];
}
}

Related

PHP array not setting custom key in a foreach loop

I'm looping through a database object returned by MySQL in CodeIgniter 2.x (PHP). The array $gifts has been declared outside the loop before it begins.
There is an inner loop and an outer loop. The outer loop generates the second array example below. The inner loop generates the problem array.
In LINE 2, $i['gifts'][$row->id_gift] correctly setting the keys with the desired id $row->id_gift. In LINE 1, it is not. The array key is being assigned numerically in order from 0-n as if it were being set with $gifts[][$sd] = $row->$sd.
Any thoughts on why?
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
foreach ($select_details as $sd)
{
$gifts[$row->id_gift][$sd] = $row->$sd; // LINE 1
$i['gifts'][$row->id_gift] = array('merchant_rank'=>$i['merchant_rank'],'rank'=>$row->rank); // LINE 2
}
}
}
$select_details = array('id_gift','id_group','rank');
Array (LINE 1) output sample:
Array (
[0] =>
Array (
[id_gift] => 392
[id_group] => 244
[rank] => 1
)
[1] => Array (
[id_gift] => 287
[id_group] => 239
[rank] => 1
)
[2] => Array (
[id_gift] => 264
[id_group] => 4
[rank] => 1)
)
Array (LINE 2) output sample (note the correct keys in the gifts array):
Array (
[0] => Array
(
[id] => 49
[id_group] => 49
[id_merchants] => 116
[gifts] => Array
(
[392] => Array
(
[merchant_rank] => 1
[rank] => 1
)
[287] => Array
(
[merchant_rank] => 1
[rank] => 2
)
[264] => Array
(
[merchant_rank] => 1
[rank] => 3
)
)
)
)
RESOLVED. See my answer below if you're curious. Thanks for your help #Spartan and #DontPanic.
Okay, I figured out the problem. And the more experienced programmers among you might not be all that surprised.
Later in the script I'm using a multidimensional array sort that's destroying the keys. I'm sure there's a way to prevent that, but that's not pertinent here.
usort($gifts, function($a, $b) {
return $a['rank'] - $b['rank'];
});

Cycling as an array returned by the method fetch_assoc () PHP & Mysqli

I ask those who have a bit of kindness to help me in this thing, I would like to cycle this dynamic array returned from a store procedure mysql, since it is dynamic and will never know the index I have no idea how to do, I know only the array with two key is the title that will give the list and arrays with [NomeProdotto] etc .. will list items.
This is Array to loop:
Array
(
[0] => Array
(
[NomeMenu] => Pizze
[IDMenu] => 1
)
[1] => Array
(
[IDMenu] => 1
[IDProdotto] => 2
[NomeProdotto] => Eurobar
[PrezzoProdotto] => 5.00
[IngredientiProdotto] => Pomodoro, Mozzarella, Patate bollite, Prosciutto
)
[2] => Array
(
[IDMenu] => 1
[IDProdotto] => 4
[NomeProdotto] => Parripusu
[PrezzoProdotto] => 6.00
[IngredientiProdotto] => Pomodoro, Mozzarella, Salsiccia, Funghi, Origano
)
[3] => Array
(
[IDMenu] => 1
[IDProdotto] => 5
[NomeProdotto] => U Chianu a Muccusa
[PrezzoProdotto] => 4.00
[IngredientiProdotto] => Pomodoro, Mozzarella, Origano
)
[4] => Array
(
[IDMenu] => 1
[IDProdotto] => 6
[NomeProdotto] => Vaddruni
[PrezzoProdotto] => 5.00
[IngredientiProdotto] => Pomodoro, Mozzarella, Piselli, Uovo, Prosciutto cotto, Funghi, Origano
)
[5] => Array
(
[NomeMenu] => Supplementi
[IDMenu] => 3
)
[6] => Array
(
[IDMenu] => 3
[IDProdotto] => 8
[NomeProdotto] => Prosciutto
[PrezzoProdotto] => 1.00
[IngredientiProdotto] =>
)
)
I solved this way
$i = 0;
$menus = array();
if ($mysqli->multi_query("CALL getMenuLocale(" . $_REQUEST['locale'] . ")")) {
while ($mysqli->more_results()) {
$mysqli->next_result();
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_all(MYSQL_ASSOC)) {
$menus[$i] = $row;
}
$result->free();
}
$i++;
}
}
but I get an error as soon as published on Godaddy :
Fatal error: Call to undefined method mysqli_result::fetch_all() on line 758
I read that the solution might be to use fetch_assoc () instead of fetch_all (), and it returns the array mentioned above, how can I cycle through php
First of all, don't use fetch_all. As the name implies, it returns the complete dataset. So use fetch_assoc, this will return a row of the result in the form of an array.
Like this:
while ($row = $result->fetch_assoc()) {
//
}
This leaves you with $row being the array with the irregular number of elements. You can also iterate through this array. So the code would look like:
while ($row = $result->fetch_assoc()) {
foreach ($row as $key => $value) {
//$key is 'IDMenu' for example
//$value is '1' for example
//you can then use these variables
}
}
This way it doesn't matter if you have 2 of 5 elements in the array, you can still use what values you have.
I also see you are trying to add the $row array to another $menus array? What is the purpose of this? Because you are essentially recreating the query result this way...
All things aside, perhaps it is a good idea to look at some tutorials if you have a hard time with working with arrays ;)

Formatting an array to order by specified unix timestamp in PHP

I have an array which has a timestamp consistently on [3] ( an example of the array data below)
I would like the array to be sorted using the timestamp. I've seen a few stackoverflow posts that apparently do this using two methods, array_multisort() and usort() but I've been unable to replicate either.
Here is what I've tried based on my own code:
Attempt 1 - I pass the array to usort, then attempt to take it apart with the foreach. Applying this method definitely changes the order of the results, but the dates seems to be no specific order (ascending, descending).
function sortArray($a1, $a2){
if ($a1[3] == $a2[3]) return 0;
return ($a1[3] > $a2[3]) ? -1 : 1;
}
usort($the_array, "sortArray");
foreach($the_array as $sh) {
$uid = $sh['uid'];
$username = $sh['username'];
$datetime = $sh['datetime'];
$type = $sh['type'];
echo "<p> $uid , $username, $datetime, $type </p>";
}
Attempt 2 - tried using array_multisor() which again gives me results in a different order but I don't understand what it is sorting by exactly.
foreach ($the_array as $key => $node) {
$timestamps[$key] = $node[3];
}
array_multisort($timestamps, SORT_ASC, $the_array);
//process the array with a foreach to show results
My theory here is that it isn't properly processing the unix timestamp and I'm not sure what I can do about that. Is it smart to take out all the characters of the timestamp so it is a simple line of numbers ( 2014-01-02 03:02:12 becomes 20140102030212 )? Or is there another way to process it with the timestamp in it's current form?
Here is an example of the data in the array:
Array
(
[0] => Array
(
[uid] => 20013
[0] => 20013
[username] => myhipswontlie
[1] => myhipswontlie
[rating] => 4.00
[2] => 4.00
[datetime] => 2014-01-27 23:40:56
[3] => 2014-01-27 23:40:56
[type] => rated
[4] => rated
)
[1] => Array
(
[uid] => 20025
[0] => 20025
[username] => brasilchika
[1] => brasilchika
[rating] => 4.00
[2] => 4.00
[datetime] => 2014-01-02 03:02:12
[3] => 2014-01-02 03:02:12
[type] => rated
[4] => rated
)
[2] => Array
(
[uid] => 10002
[0] => 10002
[username] => crtten
[1] => crtten
[datetime] => 2014-01-25 01:33:34
[2] => 2014-01-25 01:33:34
[type] => visits
[3] => visits
)
)
Your issue is your numeric keys don't seem to match up in your arrays. Sometimes the datetime is found in the 3rd key, sometime it is found in the second key (which is odd considering they look like they come from mysql_fetch_array() which will make uniform arrays).
To solve this you should use the associative array key instead:
function sortArray($a1, $a2){
if ($a1['datetime'] == $a2['datetime']) return 0;
return ($a1['datetime'] > $a2['datetime']) ? -1 : 1;
}
usort($the_array, "sortArray");

Right appraoch to use to Create csv out of php array

When i var_dump the contents of my array, i get the following results. I would like to be able to put the following contents into a csv file. For simplicity reasons, i have not displayed all the values of the array
Array
(
[0] => Array
(
[0] => NEWS 1
[1] => 00
[2] => 0
)
[1] => Array
(
[0] => NEWS 1
[1] => 01
[2] => 0
)
[2] => Array
(
[0] => NEWS 1
[1] => 02
[2] => 0
)
[3] => Array
(
[0] => NEWS 1
[1] => 03
[2] => 0
)
[4] => Array
(
[0] => NEWS 1
[1] => 04
[2] => 0
)
)
I would like to be able to insert the contents of that array into a csv file. My final csv file should like this
NEWS 1,0,0,0,0,0
I have tried several methods without sucess. So useless to post my code here. I would like to start from scratch. If some one can advise me on the right apparoach to use or propose me some code, it will be very great
I can give you this code I wrote long time ago.. it creates a csv line from an array... maybe it can inspire you. It is in a class called CSVWriter.
private static function writeFile($handle, $data, $pos) {
if(count($data) == 0) {
return false;
} else {
$element = $pos === 0 || $pos === count($data) - 1 ? $data[$pos] : ';'.$data[$pos];
$fwrite = fwrite($handle, $element);
if($fwrite === false || ($pos + 1 === count($data))) {
return $fwrite;
} else {
CSVWriter::writeFile($handle, $data, ++$pos);
}
}
}

Compare two multi-multi-dimensionals-arrays

I got the following array (shortened ... multiple dot mean that they are data there, both array start at entry 1 until the end.
Array
(
[12U_S_136_15_29_141] => Array
(
.....
[35] => Array
(
[stop_sequence] => 35
[stop_id] => 1601394
)
.....
[46] => Array
(
[stop_sequence] => 46
[stop_id] => 122052
)
[47] => Array
(
[stop_sequence] => 47
[stop_id] => 136208
)
[48] => Array
(
[stop_sequence] => 48
[stop_id] => 128163
)
)
[12U_S_141_57_6_141] => Array
(
[1] => Array
(
[stop_sequence] => 1
[stop_id] => 1601394
)
.....
[12] => Array
(
[stop_sequence] => 12
[stop_id] => 122052
)
[13] => Array
(
[stop_sequence] => 13
[stop_id] => 136208
)
[14] => Array
(
[stop_sequence] => 14
[stop_id] => 128163
)
)
)
As you can see, both array end are equal... 35 = 1, 46 = 12, ..., 48 = 14. By equal, I mean the same stop_id but will always be diffrent for stop_sequence and of course the array entry number.
I want to know how I can compare the entire array against the other so I can know if, here let's say, the second array match the first one at 100% (except we don't look for stop_sequence so this can be different. So in this case, both will be mark as "equal", but if let's say the last entry had a different stop_id (entry 48 would be != from the entry 14), the array will be mark as "not equal".
Anyone have a path to lead me ? I keep thinking but do not know how. I've tryed array_compare but this leaded to nothing :\
Thanks
EDIT
Nothing can be change to the database. Also, the array need to be created this way (with weird text, ie 12U_S_136_15_29_141). I can do whatever in PHP.
fetch the stop_id in to new array:s and compare thous
here is a useful function
function sub_array($array, $sub_key)
{
$new_array = array();
if(is_array($array) AND $array)
{
foreach($array as $key => $data)
{
$new_array[$key] = $data[$sub_key];
}
}
return $new_array;
}
then just compare the arrays
if(sub_array($a['12U_S_136_15_29_141'], 'stop_id') == sub_array($a['12U_S_141_57_6_141'], 'stop_id'))
or if you know what stop_id that matches:
$first_stop_id_list = sub_array($a['12U_S_136_15_29_141'], 'stop_id');
$secound_stop_id_list = sub_array($a['12U_S_141_57_6_141'], 'stop_id');
$matches = array_intersect($first_stop_id_list, $secound_stop_id_list);
if(!$matches)
echo "No stop_id matches";
else if($first_stop_id_list = $secound_stop_id_list)
echo "all element was in both";
else if($matches == $first_stop_id_list)
echo "all element in first was in secound";
else if($matches == $secound_stop_id_list)
echo "all element in secound was in first";

Categories