php array_intersect not functioning correctly - php

I currently have 2 arrays where i would like to compare dates in. here are how my arrays are structured:
$bholidays = array('05-05-2014','26-05-2014');
$userdaysoff = array('23-05-2014','24-05-2014','25-05-2014', '26-05-2014');
The aim is to detect whether or not a value from $userdaysoff exists in the $bholidays array.
The above works great and detects that 26-05-2014 exists in both arrays, but if the $userdaysoff array looks like this:
$userdaysoff = array('26-05-2014','27-05-2014','28-05-2014', '29-05-2014');
Then the duplicate date 26-05-2014 is not detected.
Is there any reason why this would be occuring?
here is how i run my code:
$results = array_intersect($bholidays, $userdaysoff);
if($results){
foreach($results as $result){
echo 'yes';
}
} else {
echo 'no';
}

Could you not quite simply use in_array?
$bholidays = array('05-05-2014','26-05-2014');
$userdaysoff = array('23-05-2014','24-05-2014','25-05-2014', '26-05-2014');
$count = count($userdaysoff);
for($i = 0; $i == $count; $i++) {
if(in_array($userdaysoff[$i], $bholidays)) {
echo $userdaysoff[$i] . " is in array.";
}
}

$bholidays = array('05-05-2014','26-05-2014');
$userdaysoff = array('26-05-2014','27-05-2014','28-05-2014', '29-05-2014');
$results = array_intersect($bholidays, $userdaysoff);
if($results)
{
foreach($results as $result)
{
echo 'yes';
}
}
else
{
echo 'no';
}
Run this code and check it works fine..
The output is yes.

Related

Making an Array from Database MySQL

I have database connection. I want to make an array but something is problem i think. Here is my array code:
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
foreach ($result as $row) {$data[] = $row;}
print_r($data);
$no=1;$total_deger=count($data);
echo $total_deger;
for($i=0;$i<$total_deger);$i++){
$xxx[i]="[Date.UTC(".$data[i]['year'].",".$data[i]['month'].",".$data[i]['day'].",".$data[i]['saat'].",".$data[i]['dakika'].",00),".$data[i]['Guc']."]";if($no < $total_deger){echo ",";}
echo $xxx[i];
}
When I run this code, nothing happens in page. When I write to for example 0 for i. I can see my array value. Where do I mistake?
Code with correction and suggestion (both are commented):-
<?php
error_reporting(E_ALL); // check all errors
ini_set('display_errors',1);// display those errors
$var = "SELECT SUBSTRING(KayitTarihi,1,4) AS year,SUBSTRING(KayitTarihi,6,2) AS month,SUBSTRING(KayitTarihi,9,2) AS day,SUBSTRING(KayitTarihi,12,2) AS saat,SUBSTRING(KayitTarihi,15,2) AS dakika,Guc FROM Urun WHERE Date(KayitTarihi)=\"".$link_m."\"";
$result = $mysqli->query($var);
$data = array();
if ($result->num_rows > 0) { // check you got results or not
while($row = $result->fetch_assoc()) {
$data[] = $row; // assign them
}
}
//foreach ($result as $row) {$data[] = $row;} // not needed
print_r($data);
$no=1;
$total_deger= count($data);
echo $total_deger;
for($i=0;$i<$total_deger;$i++){ // remove )
$xxx[$i]="[Date.UTC(".$data[$i]['year'].",".$data[$i]['month'].",".$data[$i]['day'].",".$data[$i]['saat'].",".$data[$i]['dakika'].",00),".$data[$i]['Guc']."]"; // use $i instead of i
if($no < $total_deger)
{
echo ",";
}
echo $xxx[$i];
}
Note:- Always add some error reporting code. So that all errors will populated and you can rectify those
Also better would be to use foreach() instead of for loop (as it will take care of indexes itself):-
//use foreach
foreach ($data as $dat){
echo "[Date.UTC(".$data['year'].",".$data['month'].",".$data['day'].",".$data['saat'].",".$data['dakika'].",00),".$data['Guc']."]";
}
Firstly you want to check your SQL query returns rows. Then I think you need to modify your foreach to a while as below. Also checking that rows are returned before looping.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}
As per example given here: http://www.w3schools.com/php/php_mysql_select.asp

Remove Duplicated Entries From an Array

For removing the duplicated entries I know I have to use array_unique() but unfortunately by using this I got unexpected result(s). My PHP code is this:
$query = $db->query("
SELECT sid,father_contact,residential_contact
FROM ".TABLE_PREFIX."student_list
{$where_clause}
ORDER BY sid ASC");
while ($s = $db->fetch_array($query))
{
if (!empty($s['father_contact']))
{
$father_contact = $s['father_contact'].', ';
}
else
{
$father_contact = '';
}
if (!empty($s['residential_contact']))
{
$residential_contact = $s['residential_contact'].', ';
}
else
{
$residential_contact = '';
}
$phone_nums_bit .= $father_contact.$residential_contact;
}
This grabs all phone numbers from the database tables and print the result like this:
03334523675, 03124237009, 03134237002, 03124237009, 03217832173, 03134237002, 3134237002, 03124237009,
Notice that few numbers like 03134237002 is repeating thrice. I want to remove duplicate entries from this result. Please help me to sort it out. Thanks.
You can try to do it via array structures. Just to give you an idea:
$phones = [];
while ($s = $db->fetch_array($query))
{
if (!empty($s['father_contact']))
{
$phones[] = $s['father_contact'];
}
if (!empty($s['residential_contact']))
{
$phones[] = $s['residential_contact'];
}
}
$phones = array_unique($phones);
// and then combine into string
$phone_nums_bit = implode(', ', $phones);

Database Query into Associative Array using PHP

I am trying to grab data from my database and place in a format so I can call field1 and return field2.
In my mind I think this:
while($row = mysqli_fetch_assoc($result)) {
$aa = $row["field1"];
$bb = $row["field2"];
}
$cc = array(“$aa”=>”$bb”);
Will compute this:
$cc = array(
"Row1a"=>"Stuff in field2 row1b",
"Row2a"=>"Stuff in field2 Row2b",
"Row3a"=>"Stuff in field2 Row3b",
"Row4a"=>"Stuff in field2 Row4b",
);
After this I will be able to:
echo $cc('Row1a');
To display:
Stuff in field2 row1b
Please try this and let me know if it meets your requirements
<?php
$result=NULL;
while($row = mysqli_fetch_assoc($result)) {
$aa = $row["field1"];
$bb = $row["field2"];
$result[$aa]=$bb;
}
echo $result['Row1a'];
?>
Edited code
Then this should meet your requirement
<?php
$search=$_POST['userText'];
$query= "SELECT * FROM table WHERE field1='".$search."';";
$result=mysql_query($query,$con);
$output=NULL;
if(mysql_num_rows($result)>0) //to check if at least 1 match found
{
$array=mysql_fetch_array($result);
$output=$array['field2'];
}
if(isset($output))
echo $output; // can be returned as needed
else
echo 'No match found';
?>
Here's one way. If there aren't an even number of elements in $row then the odd last one will be set to Last. But obviously this overwrites $result each time so you probably want a multidimensional array using a counter and $result[$i] or some such:
foreach(array_chunk($row, 2) as $pair) {
if(isset($pair[0], $pair[1])) {
$result[$pair[0]] = $pair[1];
}
}
if(isset($pair[0])) {
$result['Last'] = $pair[0];
}

PHP Query error stdClass Object ( [Id] => )

I'm executing this query on PHP:
$query = 'SELECT email__c, firstname__c FROM user__c';
$result = $mySforceConnection->query($query);
for($i = 0; $i < count($result->records); $i++) {
print_r($result->records[$i])."<br/>\n";
echo("<span>done</span><br/>\n");
}
I just have 2 elements in my database and the output is:
done
done
How I can print the values?
Salesforce returns an array of objects, try something like this instead:
$i=0;
foreach ($response->records as $record) {
$i++;
echo "\n".$i.": \n";
print_r($record);
echo "THE ID IS: ".$record->Id."\n";
}
Another point to remember with salesforce query results is if the field is empty they won't even return it in the object, so you may need to do something like this:
if (isset($record->Name)) { echo "The name is $record->Name\n"; } else { echo "name is blank\n"; }

For each PHP multi dimension array returns 1 character

For some reason the both code upon killing the query var returns:
SELECT client_fname FROM client WHERE c=:l AND f=:n
Instead of:
SELECT client_fname FROM client WHERE client_id=:id AND client_id=:fname
Notice that only the first character of the column name strings is output.
Where am I going wrong? :S
PHP 5.4, will be using PDO SQL.
public function getField($_field, $_id, $_type) {
$_args = array(
array($_type.'_id', 'id'),
array($_type.'_fname', 'fname')
);
//var_dump($_args);
echo $this->dbSelect($_type.'_'.$_field, $_type, $_args);
}
protected function dbSelect($_select, $_from, $_args) {
$i = 0; //var_dump($_args);
$query = 'SELECT '.$_select.' FROM '.$_from.' WHERE ';
foreach ($_args as $_where) {
if($i == 0) {
$query .= $_where[$i][0] .'=:'. $_where[$i][1];
} else {
$query .= ' AND '.$_where[$i][0] .'=:'. $_where[$i][1];
}
$i++;
}
die($query);
}
$_args was a 2D array. However, your foreach is using $_where as its iteration variable. $_where is itself a one-dimensional array, so you don't need $i here at all. Instead just use $_where[0]
$_where[0] should refer to the column, and $_where[1] refers to its bound placeholder. $i is unrelated to the contents of $_where.
foreach ($_args as $_where) {
if($i == 0) {
$query .= $_where[0] .'=:'. $_where[1];
} else {
$query .= ' AND '.$_where[0] .'=:'. $_where[1];
}
$i++;
}
Otherwise, you are getting the result of an array key access of a string. For example:
$str = "Hello world";
echo $str[0];
// "H"

Categories