how to handle associative array in php - php

I have written a code in php that deals with php and mysql associative array.
I have wirtten a query in SQL as
$sql=mysql_query("select x,y from table_name");
Extracted value in associative array as
while($row=mysql_fetch_assoc($sql))
{
foreach ($row as $value1=>$value) {
...........
//$a[value1]=convert($row{'y'}); //this is wrong as i am always getting {"x":"value return from function after passing $row{'y'}","y":"value return from function after passing $row{'y'}".....ans so on} i.e same value in both the key.
}
}
What my problem is I want to use some function on one of the value from associative array as convert($row{'y'}) shown above and after the value is return from the function again i want that in associative array as
{"x":"value1","y":"value return from function after passing $row{'y'}".....ans so on} again.
How do I achieve this?
Thanks in advance.

while($row=mysql_fetch_assoc($sql))
{
$row['y'] = convert($row['y']);
}

$result = array();
while($row = mysql_fetch_assoc($sql)) {
if($row == 'someCondition') {
$result = someFunction($row[]);
} else {
$result = $row[];
}
}
now $result will hold all the returned value as an associative array. you can go ahead and use nested if. if you want to add some more condition.

If I am interpreting your question right you want something like this:
while($row = mysql_fetch_assoc($sql) {
$a[] = array(
'x' => $row['x'],
'y' => convert($row['y'])
);
}
Or, if you need the data to look up the y value based on x:
$a[$row['x']] = convert($row['y']);

Related

Set Indexes on array of returned MySQL Values

Im trying to set the indexes of a 2d PHP array from numeric indexing to keys. What I have so far is :
$result = mysql_query("SELECT * FROM settings");
if(mysql_num_rows($result) > 0 ){
while($row = mysql_fetch_assoc($result)){
$dataArray[] = $row ;
}
}
$value_to_display = $dataArray[0]['value'];
However, what I'd like to be able to use is something like this :
$value_to_display = $dataArray['some_index_value']['value'];
Anyone know how I can achieve this ? Ive tried replacing making a keys array and then using combine, but I can only do this manually. Any help is appreciated!
How about
while ($row = mysql_fetch_assoc($result)) {
$dataArray[$row['somefield']] = $row;
}
Assuming that somefield is unique, you'll get an array keyed by that field's values. If you need to key names to come from somewhere else, e.g.
$keynames = array('foo', 'bar', 'baz', ....);
$idx = 0;
while($row = mysql_fetch_assoc($result)) {
$dataArray[$keynames[$idx]] = $row;
$idx++;
}
just make sure you have enough keynames to handle all the records you get back from the query.

While loop showing only one result

I want to show string outside while loop, but it only shows one result.
while($row = $result->fetch_assoc()) {
$myarr = array();
}
echo $myarr;
This shows only one result but I need all the results outside the while loop.
Could you please help me how is this possible?
I am not sure if you want the whole row returned from the query or just a single field.
If its the whole row then try
$myarr = array(); // initialize
while($row = $result->fetch_assoc()) {
$myarr[] = $row;
}
print_r($myarr);
This will give you an array containing n row arrays.
Problem :
You are just assigning the result one after again
$myarr = array();
Here, It means you're assigning the array() again and again, which replaces the old value
Solution / What You should do
1. You can assign it to an Array (Good Approach)
while($row = $result->fetch_assoc()) {
$myarr[] = $row['yourdbitem']; // or $row if you want whole row
}
print_r($myarr);
2. You can concat in each iteration (Bad Approach)
$somevariable = '';
while($row = $result->fetch_assoc()) {
$somevariable .= $row['yourdbitem']; // or $row if you want whole row
}
echo $somevariable
Note :
I have given good and bad approach to updating what you should do and what you should not do :)

Sort array by rule made of mysql select

Hello everyone I have really chalenging task I have to sort an array by condition with mysql select or by another array. Imagine something like that
$arrayINeedToSort = array(5,4,7,96,1,0,55);
// Dont know if it is important cause of next step
sort($arrayINeedToSort);
$arrayToCheckDuplicData = array();
foreach($arrayINeedToSort as $aid)
{
$sql = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId = $aid ");
$num = mysql_num_rows($sql);
if($num)
{
echo $aid;
}
else
{
// skip this id cause it is not in array but i would like to push at the end of an array again sorted
if(in_array($aid,$arrayToCheckDuplicData))
{
echo $aid;
}
else
{
$arrayINeedToSort[] = $aid;
}
$arrayToCheckDuplicData[] = $aid;
}
}
Thats my idea, pushing array values to the end of acutal array with another simple array check but i am open to different/better ideas.
UPDATE //////////////////////////////////////////////
I need to see all ids so i cant skip them and I need them sorted.
TO BE MORE SPECIFIC i would liek to have input like this
1,4,96 (of values which are in database ) 0,5,7,55 (of values which are not in databse) at the end array will look like this
$outputSortedArray(1,4,96,0,5,7,55);
Could you please be more specific in what you want. On what is the input and what you want in your output.
If you need to sort the array $arrayINeedToSort then use sort function.
Give an example of the input and output array. Also the table with condition you wanted to check.
Check the following code and verify if this is what you want:
`
$arrayINeedToSort = array(5,4,7,96,1,0,55);
$in_cond = implode(",", $arrayINeedToSort);
$arrayToCheckDuplicData = array();
$result = mysql_query("SELECT column FROM `some_table` WHERE arrayValueId IN (" . $in_cond . ") ORDER BY arrayValueId ASC");
$num = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
if (in_array($row["arrayValueId"], $arrayINeedToSort)) {
echo $row["arrayValueId"];
}
else {
if (in_array($row["arrayValueId"], $arrayToCheckDuplicData)) {
echo $row["arrayValueId"];
}
$arrayToCheckDuplicData[] = $row["arrayValueId"];
}
}
`
You can use php array sorting functions: http://www.php.net/manual/en/array.sorting.php
There is also a function called array_unique, which is delete multiple values from an array.
If you want to sort the array in the MySQL query, use "ORDER BY ASC/DESC".

One dimensional array results from SQL column

SELECT col FROM table
Say I have this query and I get the following result:
array(2) {
0 => array(1){
"COL"=>"value1"
},
1 => array(1){
"COL"=>"value2"
}
}
Is there some SQL statement I can use to get this from the same data:
array(2) {
0=>"value1",
1=>"value2"
}
I'm using zend framework and db2. If it can't be done through SQL, can it be done with Zend?
Thanks
EDIT: I should clarify, I can do this with a loop or a function. I was just wondering if there was a built-in way to do it to save a few lines of code and be all fancy smartpants.
you could try the fetchPairs() method. That might be what you're looking for, at least in a limited fashion.
The fetchPairs() method returns data in an array of key-value pairs,
as an associative array with a single entry per row. The key of this
associative array is taken from the first column returned by the
SELECT query. The value is taken from the second column returned by
the SELECT query. Any other columns returned by the query are
discarded.
You may also try and set the fetch method to Zend_Db::FETCH_COLUMN.
Zend_Db::FETCH_COLUMN: return data in an array of values. The value in
each array is the value returned by one column of the result set. By
default, this is the first column, indexed by 0.
$db->setFetchMode(Zend_Db::FETCH_COLUMN);
try a custom function like this:-
function myfuntion($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, myfuntion($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
Here is how I do it:
in my model:
public function getRecords() {
$select = $this->select();
return $this->fetchAll($select);
}
in my controller:
$records = $mdl->getRecords();
$recordsArray = $records->toArray();
I think the easiest way is :
public function my_function()
{
$db = Zend_Db_Table::getDefaultAdapter();
$results = $db->fetchAll("SELECT * FROM my_table");
/* if you want only one row, do something like this*/
/* $results = $db->fetchRow("SELECT * FROM my_table") */
return $results;
}
/* Then maybe in your controller you can call the function
and */
$results=my_function();
/*make values avelaible to the view*/
$this->view->$results=$results
Then inside the view : it depends on what your function resturns:
case: its fetchAll:
<?php foreach ($this->results as $item): ?>
<?=$item['address']?> /* access fields */
<?php endforeach ?>
case: its fetchRow: No need to use foreach().
I hope it helps.

How to Retrieve 1 Result from Custom MySQL fetch Function

Yesterday another user helped out with building a generic function for handling MySQL Queries. It looks like this:
function fetchAll($query) {
$res = mysql_query($query) or trigger_error("db: ".mysql_error()." in ".$query);
$a = array();
if ($res) {
while($row = mysql_fetch_assoc($res)) {
$a[]=$row;
}
}
return $a;
}
And to output the returned results I simply do the following:
$data = fetchAll("SELECT * FROM news_table ORDER BY id LIMIT 10");
foreach ($data as $row) {
echo $row['title'];
}
My question relates to outputting the result when there's only one result in the array. Like when displaying the current blog post of a page. I want to know if I can do it without first calling the foreach loop? Is there a way to output just the first result from the array as I do not need to loop through it.
Perhaps I could have an alternate function, as opposed to the fetchAll() one above? One that just outputs one row?
Cheers,
Scott
Yes. For example:
echo $data[0]['title'];
Basically your $data is a two-dimensional array, with the first dimension being the row number (count starts with 0), so you can access any of the rows directly if you know its number. If you only have one row, it's necessarily 0.
Just count the array
if(count($data) == 1) {
// Only one dataset
} else if(count($data) > 0) {
// foreach
} else {
// no content
}
echo $data[0]['title'];
Should print exactly what your looking for. In 2D arrays the first dimension is the array index and as array index start at 0, the above code will echo the first row in that array.

Categories