Okay I need to ask
I'm building arrays in this way:
$qe = mysql_query("SELECT * FROM table");
while ($k = mysql_fetch_object($qe)) {
$array1[] = $k;
}
and I want to add a manual key and value to $array1
I've tried $array1[]['admin']
and $array1['admin'][]
and array_push($array1['admin']=1)
and array_push($array1, 'admin' => 1)
and array_push($array1[], 'admin' => 1)
admin key is always going out of builded array
Just set a key to a value:
$array1['admin'] = 1;
Or:
$array1[] = $k + array('admin' => 1);
You are using mysql_fetch_object which returns object not array.
So you should do:
$k->admin = 1;
$array1[] = $k;
You'll need to do the following if you intend on constructing your arrays in this manner.
$qe = mysql_query("SELECT * FROM table");
while ($k = mysql_fetch_object($qe)) {
$array1[] = Array("admin" => $k);
}
Related
I have 2 SELECT statement in my PHP. Both the select statements fetch data from two different DB. The fetched data is saved in PDO Assoc Array. The problem is when I want to compare those two arrays to find that if the column 'id' exist in both arrays or not. If it exists then ignore it. If it's a unique id then save it into a third array. But I found some problems in my Logic Below
And after running the below code I am getting a couple of error:
1: Array to string conversion
2: duplicate key value violates unique constraint
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
$array1 = array();
foreach($arr1 as $x){
$array1[] = $x['id'];
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
$array2 = array();
foreach($arr2 as $y){
$array2[] = $y['id'];
}
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
All I am trying to get the unique row of data array() after comparing their id column.
You can use in_array() function as both arrays are index array.
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(count(array_intersect($array1,$array2)) <= 1){// is the count of id is 1 or less save that whole row in the $finalarray
$finalarray = $arr1[$i]; // saving the unique row.
}
else{
continue;
}
}
make change in code:
$finalarray = array();
for ($i = 0; $i < count($arr1); $i++){
if(!in_array($array1[$i], $array2)){
$finalarray[] = $array1[$i]; // saving the unique row.
}
}
You can simply use array_intersect() to get common values between two array. for difference, can use array_diff()
$array1 = [1,2,3,4,5,6,7];
$array2 = [2,4,6];
//array_intersect — Computes the intersection of arrays
$result = array_intersect($array1, $array2);
print_r($result);
//array_diff — Computes the difference of arrays
$result = array_diff($array1, $array2);
print_r($result);
DEMO
Rather than using 3 different arrays to get unique ids, you can do it by using one array. Make changes to your code as below:
$finalarray = array();
$arr1 = $msql->fetchAll(PDO::FETCH_ASSOC);
foreach($arr1 as $x){
if (!in_array($x['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $x['id'];
}
}
$arr2 = $psql->fetechAll(PDO::FETCH_ASSOC);
foreach($arr2 as $y){
if (!in_array($y['id'],$finalarray)) { // check id is already stored or not
$finalarray[] = $y['id'];
}
}
Maybe you should make sure which array is larger before your loop ;
Or using array_diff:
$finalarray = array_diff($array1 , $array2) ?? [];
$finalarray = array_merge( array_diff($array2 , $array1) ?? [], $finalarray );
I'm making a simple search engine, and I have already indexed a lot of websites in a MySQL database. Now I would like to get a relevant list of results by keywords.
Websites are indexed in my database with the following columns : hostname (without protocol an port), title, description. (We don't care about path)
When I type some keywords on my search engine homepage, it first starts by fetching 50 websites using FULLTEXT indexes.
Now, and because using Levenshtein algorithm in MySQL is really slow, I would like to sort those results with the Levenshtein PHP function for each columns I listed previously.
I would like to sort them in this order (most important first) : hostname, title, and then description.
So I have five arrays :
$results, returned by MySQL
$sorted_by_mysql, containing keys of $results in the original order : 0, 1, 2, ...
$sorted_by_hostname, containing keys of $results sorted by hostname's relevance using Levenshtein, ex: 3, 0, 1, 2, ...
$sorted_by_title, containing keys of $results sorted by title's relevance using Levenshtein, ex: 0, 2, 1, 3, ...
$sorted_by_description, containing keys of $results sorted by description's relevance using Levenshtein, ex: 1, 3, 0, 2, ...
Here's the code :
$results = $req->fetchAll();
$search = strtolower($q);
$temp_arr = [];
$sorted_by_mysql = $sorted_by_hostname = $sorted_by_title = $sorted_by_description = [];
// We keep the original order in an array
for($i = 0; $i < count($results); $i++) $sorted_by_mysql[] = $i;
// Sort by hostname
for($i = 0; $i < count($results); $i++) $temp_arr[$i] = levenshtein($search, strtolower($results[$i]->hostname));
asort($temp_arr);
foreach($temp_arr as $k => $v) $sorted_by_hostname[] = $k;
// Sort by title
for($i = 0; $i < count($results); $i++) $temp_arr[$i] = levenshtein($search, strtolower($results[$i]->title));
asort($temp_arr);
foreach($temp_arr as $k => $v) $sorted_by_title[] = $k;
// Sort by description
for($i = 0; $i < count($results); $i++) $temp_arr[$i] = levenshtein($search, strtolower($results[$i]->description));
asort($temp_arr);
foreach($temp_arr as $k => $v) $sorted_by_description[] = $k;
Finally I would like to sort $results by combining (by priority) all thoses different arrays. But I have no idea on how, so here's where I need some help !
EDIT : Solution !
$data = $req->fetchAll();
$search = strtolower($q);
$temp = [];
foreach($data as $i => $row) {
$temp[] = [
'id' => $i,
'lev1' => levenshtein($search, strtolower($row->hostname)),
'lev2' => levenshtein($search, strtolower($row->title)),
'lev3' => levenshtein($search, strtolower($row->description))
];
}
$sorted = array_orderby($temp, 'lev1', SORT_ASC, 'lev2', SORT_ASC, 'lev3', SORT_ASC, 'id', SORT_ASC);
$results = [];
foreach($sorted as $row) {
$results[] = $data[$row['id']];
}
// Perfectly sorted !
Here's array_orderby function :
// Credits : jimpoz at jimpoz dot com (PHP.net)
function array_orderby()
{
$args = func_get_args();
$data = array_shift($args);
foreach ($args as $n => $field) {
if (is_string($field)) {
$tmp = array();
foreach ($data as $key => $row)
$tmp[$key] = $row[$field];
$args[$n] = $tmp;
}
}
$args[] = &$data;
call_user_func_array('array_multisort', $args);
return array_pop($args);
}
See the answer to this SO question, they have a similar need but have structured their data in a way that makes the answer easier. It looks like PHP supports sorting by multiple attributes (in descending priority) as long as those attributes are built into the associative array that's being sorted.
To apply this approach to your data, you'll probably want to restructure your results into one giant associative array where each element of the array contains a value for each "field" you're aiming to sort by. Does that make sense?
Good luck!
I have 2 2D arrays, how can i get the unique keys and only push those? For example:
$array = json_decode('[{"7654321":1368356071},{"1234567":1368356071}]',true);
$array2 = array(array(1234567 => time()), array(7654321 => time()), array(2345678 => time()));
//array_push($array, $array2[2]);
-- How can I dynamically get the unique key like $array2[2] in this example?
why not to use array_unique() function in php? http://php.net/manual/ru/function.array-unique.php
You mean, you would like to push into another array (let's say in $keys_unique) whatever key(s) that are present only in one of the first two arrays, but not present in both of them?
Try this:
$arrays_mixed = array( //your $array and $array2; you can put as many arrays as you want here
json_decode('[{"7654321":1368356071},{"1234567":1368356071}]',true)
,array(array(1234567 => time()), array(7654321 => time()), array(2345678 => time()))
);
//begin getting all keys
$arrays_keys = array(); //will hold all keys from arrays_mixed
$keys_unique = array(); //will hold all unique keys out of arrays_key
for($x=0;$x<count($arrays_mixed);$x++){
$arrays_keys[$x] = array(); //prepares a "keys holder"
$toflatten = $arrays_mixed[$x];
$c1 = 0;
do{
$arrmixed = array();
$arrclean = array();
foreach($toflatten as $a){
$arrmixed = $this->keys_finder($a,1);
$arrclean[$c1] = $this->keys_finder($a,2);
$c1++;
}
$toflatten = $arrmixed;
}while(is_array($toflatten));
for($c2=0;$c2<$c1;$c2++)
foreach($arrclean[$c2] as $ac)
array_push($arrays_keys[$x],$ac);
}//end geting all keys
//begin finding unique keys
foreach($arrays_keys as $ak)
foreach($ak as $add)
$keys_unique = $this->unique_inserter($arrays_keys,$keys_unique,$add);
//end finding unique keys
Here are the functions you need
function unique_inserter($arrays_keys,$keys_unique,$add){
$detector = 0; //detects how many arrays contain a value
foreach($arrays_keys as $ak)
if(in_array($add,$ak))
$detector++;
if($detector<2) //if value is found in one array only
array_push($keys_unique,$add);
return $keys_unique;
}
function keys_finder($array,$return){
$arrmixed = array();
$arrclean = array();
foreach($array as $key=>$a)
if(is_array($a))
foreach($a as $aa)
array_push($arrmixed,$aa);
else
array_push($arrclean,$key);
switch($return){
case 1:
return (count($arrmixed)==0)?'':$arrmixed;
break;
case 2:
return $arrclean;
break;
}
}
I have tested this code and it works on my side. Hope it helps.
I want to create an associative array in php with dynamic key and also a dynamic value from a particular mysql table.
The table name is monthly_salary with a two column named month and salary respectively.
I get the data inside it:
$sql = mysql_query('SELECT * FROM monthly_salary');
$sql2 = mysql_query('SELECT * FROM monthly_salary');
Then assigned and concatenated the collected data to $mon and $sal:
$mon = "";
$sal = "";
while($row = mysql_fetch_array($sql)){
$mon .= $row['month'].", ";
}
while($row = mysql_fetch_array($sql2)){
$sal .= $row['salary'].", ";
}
After that I've converted it to array and concatenate it until it became and associative array:
$monArray = array(substr(trim($mon), 0, -1));
$salArray = array(substr(trim($sal), 0, -1));
$key = "";
$keyWithVal = "";
foreach($monArray as $k){
$key .= $k." => ";
}
foreach($salArray as $k){
$keyWithVal .= $key.$k.",";
}
$associativeArray = array(substr(trim($keyWithVal), 0, -1));
My Problem is that when I've echo it the result is always like this
3500=>Jan=>3500:
foreach($associativeArray as $k => $id){
echo $k."=>".$id;
}
So how can I fix it and with the correct output Jan=>3500?
You are way over-complicating this problem. This can be done simply, with fewer loops.
First, you only need to run the SQL once. Second, build the array in the 1st loop.
$sql = mysql_query('SELECT * FROM monthly_salary');
$associativeArray = array();
while($row = mysql_fetch_array($sql)){
// Put the values into the array, no other variables needed
$associativeArray[$row['month']] = $row['salary'];
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id;
}
Why don't you just do:
$associativeArray = array();
while($row = mysql_fetch_array($sql)){
$associativeArray[$row['month']] = $row['salary'];
}
Following worked for me for creating associative array. array_push don't work on associative array but using unary operator does work:
$associativeArray += [$key => $value];
I have an array like:
$arr[0] = ("1-3-2011","1","15"); //date(dd-mm-yyyy),id,amt
$arr[1] = ("1-4-2011","2","5");
$arr[2] = ("12-3-2011","6","20");
$arr[3] = ("1-3-2011","10","10");
$arr[4] = ("12-3-2011","3","10");
$arr[5] = ("1-4-2011","5","15");
$arr[6] = ("1-3-2011","7","15");
From this I need to generate a condensed array like
$newarr[0] = ("1-3-2011","1,7,10","40");
$newarr[0] = ("1-4-2011","2,5","20");
..
...
Basically the first one is a multidimentional array, containing date,id, and amount. In the new array, I need to condense the previous one for each unique date, ids as a csv string for duplicate dates, and amounts added.
What's the most efficient way to do this, performance wise?
Something like this should do it:
$newarr = array();
foreach($arr as $row) {
if(!isset($newarr[$row[0]])) {
$newarr[$row[0]] = array('ids' => array(), 'amount' => 0);
}
$newarr[$row[0]]['ids'][] = $row[1];
$newarr[$row[0]]['amount'] += $row[2];
}
foreach($newarr as $key => &$row) {
$row = array($key, implode(',', $row['ids']), $row['amount']);
} unset($row);
Working example:
http://codepad.org/UmiDKLYJ