This question already has answers here:
mysql_fetch_array returns duplicate data
(7 answers)
Closed 9 years ago.
Maybe I have long since gotten to used to using ORM methods to pull data from a DB but I am now working up a simple little project for a buddy of mine who doesn't need all the extra guff of MVC's, ORM's and so on.. With that below is an example of the query I am putting together in a class I am building up in PHP.
$this->sqlstart();
$sql = "select label, setting from ".$this->_settings." where id <= 4";
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($query))
{
$result[] = $row;
}
return $result;
The output from return $result is:
Array
(
[0] => Array
(
[0] => Week 1 Pay
[label] => Week 1 Pay
[1] => 2995
[setting] => 2995
)
[1] => Array
(
[0] => Week 2 Pay
[label] => Week 2 Pay
[1] => 2995
[setting] => 2995
)
[2] => Array
(
[0] => Week 1 Dates
[label] => Week 1 Dates
[1] => 1-15
[setting] => 1-15
)
[3] => Array
(
[0] => Week 2 Dates
[label] => Week 2 Dates
[1] => 16-31
[setting] => 16-31
)
)
And it should be
Array
(
[0] => Array
(
[label] => Week 1 Pay
[setting] => 2995
)
[1] => Array
(
[label] => Week 2 Pay
[setting] => 2995
)
[2] => Array
(
[label] => Week 1 Dates
[setting] => 1-15
)
[3] => Array
(
[label] => Week 2 Dates
[setting] => 16-31
)
)
can anyone point out to me where the additional data in the sets is coming from?
You should use mysql_fetch_assoc to get the result properly. It will provide you an associative array instead of a normal one.
From http://php.net/manual/en/function.mysql-fetch-array.php
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
Either pass MYSQL_ASSOC as the second param to just get an associative array back, or just call mysql_fetch_assoc().
You should be able to pass in a second argument which will only output the associative column names:
while($row = mysql_fetch_array($query, MYSQL_ASSOC))
mysql_fetch_array returns two ways to access values: field name and index number. You might change mysql_fetch_array to mysql_fetch_assocor change the code to:
while($row = mysql_fetch_array($query)){
$result[] = array('label' => $row['label'], 'setting' => $row['setting'];
}
Related
I have a large object API response, I'm trying to load the data into a nested array so I can work with it later. Here is a sample of the object I get back from the API.
SObject Object
(
[type] => AggregateResult
[fields] => stdClass Object
(
[expr0] => 12
[Name] => Performance Reviews
[Status] => Closed - Approved
[expr1] => 30
)
)
SObject Object
(
[type] => AggregateResult
[fields] => stdClass Object
(
[expr0] => 12
[Name] => Performance Reviews
[Status] => Closed - Attempted
[expr1] => 11
)
)
SObject Object
(
[type] => AggregateResult
[fields] => stdClass Object
(
[expr0] => 12
[Name] => Performance Reviews
[Status] => Closed - Contact Declined
[expr1] => 13
)
As I said, the goal is to have a nested array that would look similar to this:
Array
(
[January] => Array
(
[0] => Array
(
[0] => January
[1] => Closed - Approved
[2] => 28
)
[1] => Array
(
[0] => January
[1] => Closed - Approved
[2] => 28
)
)
)
Here is my Code:
$query =
"SELECT CALENDAR_MONTH(closedDate), recordType.name,status,count(id)
FROM case
WHERE owner.name ='" . $SFName . "' AND recordType.name IN('DT Case','Performance Reviews') AND closedDate = LAST_N_MONTHS:6
GROUP BY CALENDAR_MONTH(closedDate),recordType.Name,status ORDER BY CALENDAR_MONTH(closedDate)";
$counter = 0;
$mprArray = array(); //instantiate our Array
$response = $mySforceConnection->query($query);
$queryResult = new QueryResult($response);
foreach ($queryResult->records as $case) {
//turn our query Result into an Obj
$sObject = new SObject($case);
$recordType = $sObject->Name;
$status = $sObject->Status;
$month = $sObject->expr0;
$count = $sObject->expr1;
//this is a filter to weed out a portion of the cases.
if ($recordType == "Performance Reviews") {
foreach($sObject as $record) {
//change the month's number to a month's name
$dateObj = DateTime::createFromFormat('!m', $month);
$monthName = $dateObj->format('F');
// Create the nested array, it should end up looking like $mprArray[January].
// This is a dynamic name since we're creating an array for each status that exists in performance Reviews
$mprArray[$monthName] = array($monthName,$status,$count);
// Trying to append our nested array onto the $mprArray so we can work with it later.
array_push($mprArray,$mprArray[$monthName]);
}
}
//increase counter
$counter = $counter++;
}
} catch (Exception $e) {
print_r($mySforceConnection->getLastRequest());
echo $e->faultstring;
}
Instead of a nested array, only the first item in the array is named 'January', the remainder are named based on a counter, until we get to the next month of 'february', here's what it looks like.
Array
(
[January] => Array
(
[0] => January
[1] => Closed - Contact Declined
[2] => 15
)
[0] => Array
(
[0] => January
[1] => Closed - Approved
[2] => 28
)
)
because array_push only inserts the data to the next index;
I feel you should use $mprArray[$monthName][] = array($monthName,$status,$count); only; and no need for the array_push after that
This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 4 years ago.
I'm trying to query database A and store results as an array, which I will then insert into database B. I can move simple data directly, but because of the complexity of this particular query (30+ left joins), I have to store it as an array and insert it in a separate query. The examples below contain just two fields, to keep things simple and focus on the core issue.
I have working code to insert an array stored as follows:
$data = array(
array( // record 1, or row 1
"1",
"Value for field 1.2"
),
array( // record 2, or row 2
"2",
"Value for field 2.2"
),
array( // record 3, or row 3
"3",
"Value for field 3.2"
),
// etc...
);
Unfortunately, I can't get my first query to store the data like this. I have used PHP for years, but I never messed with arrays before. I'm not sure what I'm doing wrong. Using "print_r($data), this is what the results look like for how I need the array to be (This is what the $data variable looks like with print_r() ):
Array ( [0] => Array ( [0] => 1 [1] => Value for field 1.2 ) [1] => Array ( [0] => 2 [1] => Value for field 2.2 ) [2] => Array ( [0] => 3 [1] => Value for field 3.2 ) )
My query to create the array doesn't match this pattern. A "print_r($new_array)" command yields this:
Array ( [0] => Array ( [id] => 37 [post_title] => test1 ) [1] => Array ( [id] => 38 [post_title] => test2 ) [2] => Array ( [id] => 35 [post_title] => test3 ) [3] => Array ( [id] => 42 [post_title] => test4 ) [4] => Array ( [id] => 44 [post_title] => test5 ) [5] => Array ( [id] => 46 [post_title] => test6 ) )
This is my MySQL query to put the data into an array:
$test_sql = "SELECT id, post_title FROM wp_posts where post_type LIKE 'test'";
$resultTest = mysqli_query($con, $test_sql);
//$new_array[] = $row;
while ($row = mysqli_fetch_assoc($resultTest)) {
$rows[] = $row;
}
If I understand what is going on, the array I'm creating is making key value pairs for a multidimensional array, but the format I need is not key value, just an array of values. Since I already have the insert query working, I would prefer to use a select query that stores the data in an array without the key value pairs, if that is possible, but I am open to all suggestions.
Thank you in advance for your kindness and help!
All you need to do is change fetch function to fetch_row:
while ($row = mysqli_fetch_row($resultTest)) {
$rows[] = $row;
}
Or to fetch_array with MYSQLI_NUM as second argument:
while ($row = mysqli_fetch_array($resultTest, MYSQLI_NUM)) {
$rows[] = $row;
}
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 ;)
This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
I have been tried couple of times before asking here, i've also seen this question
which is similar to mine but unfortunatly it doesnt work (or i can get it working as well).
I have an array like this:
Array (
[user_1] => Array
(
[0] => Array
(
[category] => string_var
[time] => unix_timestamp
),
[1] => Array
(
[category] => string_var
[time] => unix_timestamp
),
[2] => Array
(
[category] => string_var
[time] => unix_timestamp
)
),
[user_2] => Array
(
[0] => Array
(
[category] => string_var
[time] => unix_timestamp
),
[1] => Array
(
[category] => string_var
[time] => unix_timestamp
),
[2] => Array
(
[category] => string_var
[time] => unix_timestamp
)
)
)
And for each user i have to sort the 2nd-level array by timestamp.
Hence, i've tried:
foreach ($array as $user => $user_data) {
timestamps = array();
foreach($user_data as $key => $actual_data) {
$timestamps[$key] = $actual_data['time'];
}
array_multisort($timestamps, SORT_ASC, $user_data);
}
unset($timestamps);
print_r($array); // the original array should now be sorted by timestamp
Well, no sorting happens, the final array is exactly = the original one.
NOTES :
the key ['time'] into the 2nd-level array comes from a MYSQL column
and it's stored as BIGINT. var_dump gives me: int(1432587949), so it shouldnt be a variable type issue
i have also tried usort, with the same result: no sorting.
Where am i wrong? thanks
You want to do something like this:
array_walk($array, function(&$arr) {usort($arr, function($a,$b){return ($a["time"] < $b["time"]) ? -1 : ($a["time"] > $b["time"] ? 1 : 0);});});
But since you said that the data come from a database then I suggest you sort them there because it's likely to be faster than sorting it 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");