I have a column that contain integer values. I join all columns by doing
"SELECT GROUP_CONCAT(column) AS column"
Then I build an array doing
while ($row = $result->fetch_assoc()){
$employees[] = $row['column'];
}
print_r($employees) returns Array ( [0] => 1,2,3,4,68,25,1 )
So I want to remove the duplicate 1 and for that I use array_unique
print_r(array_unique($employees));
This still brings back Array ( [0] => 1,2,3,4,68,25,1 )
What am I doing wrong here
Solution at SQL side:
SELECT GROUP_CONCAT(DISTINCT column) AS column
if you want an ordered list:
SELECT DISTINCT column ORDER BY Column
and then store all rows by
while(...) $employees[] = $row['column'];
The problem is that you are trying to use array_unique() on a string, which won't really do anything.
You can break this string into an array by using the explode() function.
$unique = array_unique(explode(',', $employees[0]);
Alternatively, you could just check inside your loop if a value has already been put into an array using in_array().
while ($row = $result->fetch_assoc()){
if(!in_array($row['column'], $employees)) {
$employees[] = $row['column'];
}
}
Just use the array_map function. And map all value with intdiv function
$employees = array_unique(array_map("intdiv", $employees));
print_r($employees);
Related
I have an array like this
$EN=array(
"text1"=>"translation1",
"text2"=>"translation2",
"text3"=>"translation3",
"text4"=>"translation4",
);
and this is my query
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN';";
$test= $conn->query($result);
The langVar column will retrieve text variables and the translation column is for translation words.
$EN=array(
foreach ($test AS $row){
$row['langVar']=>$row['$translation']
}
);
but it was a syntax error
Please, how can I do this the right way ?
You can't put a loop inside an array literal.
Add to the array inside the loop, not the other way around:
$EN = [];
foreach ($test as $row) {
$EN[$row['langVar']] = $row['translation'];
}
DEMO
You don't need a loop. If you only want to fetch all rows into a multidimensional array indexed by one of its columns, you cause use fetch_all() and array_column().
$result = "SELECT langVar, translation FROM lang WHERE langName = 'EN'";
$EN = array_column($conn->query($result)->fetch_all(), 0, 1);
I have a PHP page used by an Ajax call that I want to return an ordered list of items as JSON. However whichever field I use in the query's 'order by' clause the array is always ordered by its key, the ID field.
Is there a way to preserve the insert order of each item in the PHP array?
This is the code that generates the JSON array:
$Soggetti = array();
while($row = $db->fetch_array($query))
{
$Soggetti[$row['ID']] = array();
$Soggetti[$row['ID']]['Denominazione'] = $row['Denominazione'];
$Soggetti[$row['ID']]['Indirizzo'] = $row['Indirizzo'].','.$row['Comune'].', '.$row['Provincia'];
$Soggetti[$row['ID']]['Superficie'] = $row['Superficie'];
$Soggetti[$row['ID']]['Lat'] = $row['Lat'];
$Soggetti[$row['ID']]['Lng'] = $row['Lng'];
$Soggetti[$row['ID']]['Tipologia'] = $row['Tipologia'];
$Soggetti[$row['ID']]['CodiceIscrizione'] = $row['CodiceIscrizione'];
$Soggetti[$row['ID']]['Visitato'] = intval($row['Visitato']);
}
echo json_encode($Soggetti)
If the problem lies in where the JSON is interpreted, in the client, you can use this syntax to return a JSON array (enclosed in []) instead of a JSON object (enclosed in {}).
echo json_encode(array_values($Soggetti));
You are building a 2 dimensional array with the key on first dimension being the id. Assuming id is numeric you will end up with nested objects in JSON, with the key of top level being the numerical id values. The problem here being that object properties have no guarantee of order.
To get the order of the query results, simply build a 1-D array inside your result set loop like this:
$tempArray = array();
$tempArray['ID'] = $row['ID'];
$tempArray['Denominazione'] = $row['Denominazione'];
$tempArray['Indirizzo'] = $row['Indirizzo'].','.$row['Comune'].', '.$row['Provincia'];
$tempArray['Superficie'] = $row['Superficie'];
$tempArray['Lat'] = $row['Lat'];
$tempArray['Lng'] = $row['Lng'];
$tempArray['Tipologia'] = $row['Tipologia'];
$tempArray['CodiceIscrizione'] = $row['CodiceIscrizione'];
$tempArray['Visitato'] = intval($row['Visitato']);
$Soggetti[] = $tempArray;
The will encode to JSON as an array of objects with the array numerically indexed from 0 based on order in result set.
You need an ORDER BY clause of your MySQL statement.
In this case you want to order by your id, and in ascending order, so;
SELECT * from your_table ORDER BY id ASC
Reference: MySQL Sorting
The problem may lie in your mysql query, try:
select * from table_name order by ID asc
Using select query am select some data from database.
i fetched data using while loop.
while($row=mysql_fetch_array($query1))
{
}
now i want to print only index of $row.
i tried to print using following statements but it prints index and value(Key==>Value)
foreach ($row as $key => $value) {
echo $key ;
}
and i tried array_keys() also bt it is also not helpful to me.
echo implode(array_keys($row));
please help to get out this.
i need to print only index.
You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.
If you need just the numeric array, use:
while($row=mysql_fetch_array($query1, MYSQL_NUM))
By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.
You should pass separator(glue text) in Implode function.
For comma separated array keys, you can use below code.
echo implode(",",array_keys($row));
The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.
Store each $row in an array, like so:
$arr = array();
while($row=mysql_fetch_array($query1)) {
$arr[] = $row;
}
Now, to print the array keys, you can use a simple implode():
echo implode(', ', array_keys($arr));
$query1 from while($row=mysql_fetch_array($query1)) should be the result from
$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))
To get only the keys use mysql_fetch_row
$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
print_r(array_keys($row));
}
I want to explode an array, read each value and print them back in an array...
I dont understand where i am getting wrong. Please help me..this is my code..
I am getting an array to string conversion error
$query="SELECT categories FROM shops";
$result = mysql_query($query);
while($column = mysql_fetch_assoc($result)){
$categories=explode(",",$column['categories']);
foreach($categories as $value){
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
array_push($shops_list,$name_column);
}
}
echo implode(",",$shops_list);
$shop_list is not defined, before using it in this line array_push($shops_list,$name_column);. And, this line
array_push($shops_list,$name_column);
needs to be, as you need to mention the key name,
array_push($shops_list,$name_column['name']); //or better
$shop_list[] = $name_column['name'];
Several issues:
$name_column = mysql_fetch_assoc($name);
$name_column = $name_column['name'];
name_column is an array.
shops_list is never initialized.
You should use [] instead of array_push.
The other guys hit it on the nose, but when you did your array push on $name_column, since $name_column is an array, you end up with:
Array
(
[0] => Array
(
[name] => boo
)
)
Obviously doing an implode on that is going to not work.
That being said, what you really need to do here is not keep your category mappings as a comma delimited string in the database. Standard DB architecture dictates you use a mapping table.
Table shops
Table categories
Table shop_category_map that has shop_id and category_id
use group_concat to retrieve values. and after getting the result, use them directly for searching. like
$result_array = explode(",",$row['category']);
foreach($result_array as $ra)
{
//sql command. fetch here.
$new_query="SELECT name from categories where id='$value'";
$name = mysql_query($new_query);
$name_column= mysql_fetch_assoc($name);
$shops_list[] = $name_column;
}
try else go for better solution
// explode an array and then implode until a particular index of an array
$a = '192.168.3.250';
$b = explode('.',$a);
$ar = array();
for($i=0;$i<=2;$i++)
{
array_push($ar,$b[$i]);
}
$C = implode($ar,'.');
print_r($C);
I want to select the most recent 12 rows from a table, but then shuffle the order.
So i cant use ORDER BY RAND() becouse that would just randomly pick some rows and not the most recent 12 rows.
I was thinking something like this, but it didnt work out as planned:
$artig_photos = mysql_query("
SELECT photo_id, photo_name
FROM `migo_artig_photos`
WHERE (
photo_deleted=0 AND photo_type=2
)
ORDER BY photo_id DESC
LIMIT 12;
");
while ($row = mysql_fetch_array($artig_photos)) {
$artig_shuffled[$row['photo_id']] = $row['photo_name'];
}
shuffle($artig_shuffled);
later when i do:
foreach ($artig_shuffled as $key => $value) {
}
i expected the key to be photo_id and the value to be photo_name with the correct relation between them, guess i was wrong.
Any tips about how to solve this problem? Maybe my approach isnt good at all.
Best of regards,
Alexander
You could put them all in an array in PHP, then randomize the order of that array with shuffle(), or make the query to select the most recent 12 a sub query, then randomize the results with the outer query. Just store the items with $items[] = $row;, then shuffle($items); and iterate over it. You wont get the $photo_id in $key, but it will still be in $item['photo_id']
PHP's shuffle() function removes any existing keys from your array:
Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
This function is best used with numerically indexed arrays. A quick approach would be to just write your own shuffle function that works on associative arrays. I found this one on a previous Stack Overflow post:
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[] = $list[$key];
}
return $random;
}
Link to the original:
PHP Random Shuffle Array Maintaining Key => Value
You could use a subquery:
SELECT * FROM (
SELECT `migo_artig_photos`.`photo_id`,
`migo_artig_photos`.`photo_name`
FROM `migo_artig_photos`
WHERE `migo_artig_photos`.`photo_deleted` = 0 AND
`migo_artig_photos`.`photo_type` = 2
ORDER BY photo_id DESC
LIMIT 12) `top_12_migo_artig_photos`
ORDER BY RAND();
Alternatively, you could do this:
// To shuffle:
while ( $row = mysql_fetch_array($artig_photos) )
{
$artig_shuffled[] = $row;
}
shuffle($artig_shuffled);
// To display:
foreach ( $artig_shuffled as $row )
{
echo $row['photo_id'];
echo $row['photo_name'];
}