I am using a PDO approach to get an array out of database:
$statement = $db->prepare("SELECT sname FROM list WHERE ongoing = 1;");
$statement->execute();
$snames = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($snames);
The dump output is (total 2500 results):
[69]=> string(13) "ah-my-goddess"
[70]=> string(17) "ahiru-no-oujisama"
[71]=> string(13) "ahiru-no-sora"
Then I check if array $snames contains the new element $sname:
$sname = current(explode(".", $href_word_array[count($href_word_array)-1]));
if (in_array($sname, $snames) == False)
{
echo "New '$sname'!<br>";
}
else
{
echo "$sname is already in the list. Excluding.<br>";
unset($snames[$sname]);
}
And the output is:
'ah-my-goddess' is already in the list. Excluding.
New 'ahiru-no-oujisama'!
'ahiru-no-sora' is already in the list. Excluding.
Why does it says that 'ahiru-no-oujisama' is the new name? We can see from the DUMP function that the array contains this element.
I have compared the results a thousand times. Notepad finds both names. There are no spaces. Name in the database is the same as in variable..
For the record - I have around 2500 entities in $snames array and for 95% of records (+-) I am getting the "already exists" result. However, for some I am getting "new".
Is that perhaps some kind of encoding issue? For the table I have DEFAULT CHARSET=latin1. Could that be a problem?
Edit
It was suggested that I added a trim operation:
$snames = $statement->fetchAll(PDO::FETCH_COLUMN, 0);
for ($i=0; $i < Count($snames); $i+=1)
{
$snames[$i] = trim($snames[$i]);
}
and:
if (in_array(trim($sname), $snames) == False)
However I get the same problem.
Apparently, the problem was with line:
unset($snames[$sname]);
for some entries I had names such as "70" and "111"
as the result command:
unset($snames[$sname]);
removed elements at that position. Not the elements with such keys!! I.e. That's how program understood it:
unset($snames[77]);
and that's what I was expecting:
unset($snames['77']);
so the line had to be changed to following:
if(($key = array_search($sname, $snames)) !== false)
{
unset($snames[$key]);
}
Related
What is the correct syntax to detect an empty 2 Dimensional array in PHP? I have attempted to do so myself using the functions "isset()" and "!empty()" for both "2dArray[0]" and "2dArray[0][0]", but even with an empty array the result comes back positive. Here is a snippet of code from one of the times where I tried this:
if(isset($strengths[0][0]) || isset($sizes[0][0]))
{
print_r($strengths[0][0]);
echo "<br>blah<br>";
print_r($sizes[0][0]);
}
Yet the arrays are both empty. Using print_r we can even see that the arrays return nothing. Here is a picture example of a different attempt using isset(2dArray[0]):
In the picture you can see the array is also empty again.
It's important to note that I can use 2dArray[1] perfectly; it detects that there there is no second row as expected, but that means I cannot have any instances where there is only 1 row in either 2D array because it is positioned at position 0 with nothing at position 1 to be detected anyway.
What am I doing wrong?
Edit 1:
The code:
var_dump($strengths[0][0]);
var_dump($sizes[0][0]);
returns:
array(0) { }
array(0) { }
and the code:
var_dump($strengths[0]);
var_dump($sizes[0]);
returns:
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
Edit 2:
This is my init:
$sizes[][] = array();
This is where data is set:
foreach($products as $product)
{
//product information
foreach($mods as $mod)
{
//mod information
//when array is empty $mods is empty
if ($modType == "SIZE")
{
$sizes[$si][0] = $modValue . $modValueSuffix;
$sizes[$si][1] = $modPrice;
$sizes[$si][2] = $modID;
$si++;
$strengthOrSize = true;
}
}
}
I believe I should have done $sizes[] = array(); for a 2D array. I overlooked this because it's such a short piece of code I did not give it much attention.
You can do this to detect if the sub array is empty:
$arr = [[]];
if (!count($arr[0])) {
// do stuff
}
I'm trying to get user information from my Active Directory through LDAP. Im using for loops to retrieve each username for a specific AD OU. All results are showing in one line without any separation. If i put
$LDAP_CN into array it just creates a lot of different arrays.
Here is my PHP code:
$entries = ldap_get_entries($ldap_connection, $result);
for ($x=0; $x<$entries['count']; $x++){
$LDAP_CN = "";
if (!empty($entries[$x]['cn'][0])) {
$LDAP_CN = $entries[$x]['cn'][0];
if ($LDAP_CN == "NULL"){
$LDAP_CN = "";
}
}
echo($LDAP_CN);
}
output:
Name LastnameName1 Lastname1Name2 Lastname2Name3 Lastname3Name4 Lastname4 ant etc.
When i try to var_dump $LDAP_CN it gives output like that:
string (13) "Name Lastname"
string (15) "Name1 Lastname1"
string (15) "Name2 Lastname2"
string (15) "Name3 Lastname3"
string (15) "Name4 Lastname4"
etc..
So i'm guessing that it knows how to separate them. But how ? I tried explode it just creates a lot of arrays.. Also if i put echo out of the loop it just returns last result.
All results in one array:
$LDAP_CN = [];
for ($x=0; $x<$entries['count']; $x++){
if (!empty($entries[$x]['cn'][0])) {
$LDAP_CN[] = $entries[$x]['cn'][0] == "NULL" ? "" : $entries[$x]['cn'][0];
}
}
print_r($LDAP_CN);
I have a multi-query MySQLi statement that uses multiple queries and when using var_dump brings back the following:
var_dump of array:
array(1) { ["company"]=> string(8) "ffr3e456" ["high_1"]=> string(8) "8.32465" }
array(2) { ["company"]=> string(8) "gg8751hw" ["high_2"]=> string(7) "7.66574" }
The code I am using to display the array in a PHP file picks up the first array (i.e. the content of high_1 information but not the second.
code
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
for ($p=1; $p<=2; $p++)
{
echo number_format($row["high_".$p],2);
The HTML output shows the data from the first array but not the second. I am sure I am overlooking something, any advice and feedback welcomed.
$C = array_merge($A, $B);
You can read more here: http://www.php.net/manual/de/function.array-merge.php
It would be helpful if you showed the SQL statement that returns the results.
Are the returned arrays in separate $row results?
In that case you need to iterate through each $row result, something like:
foreach($query->result() as $row)
{
for ($p=1; $p<=2; $p++)
{
echo number_format($row["novhigh_".$p],2);
}
}
On a side note: It looks like the key definition inside the arrays is not logical, why not have the same key value for the "novhigh" element?
I am working on a CakePHP 2.x but right now my question has nothing to do with the syntax. I need a solution for this problem:
I have a table named messages in which there is a field name mobile numbers. The numbers are in this format:
12345678 and +9112345678 .. so they are both the same. The only difference is that in one number the country code is missing.
So I do this query in the database:
select the distinct numbers from messages tables..
Now it is taking these both numbers as distinct. But what I want is to take these both numbers as one.
How can I do this? In my DB there are several numbers with different country codes. Some have a country code and some don't, but I want to take both as one. The one in country code and the other without code. How can this be done?
At times now I have an array in which all the distinct numbers are stored. In this array there are numbers like this:
12345678 +9112345678
So now I don't know how to make a logic that I can take these numbers as one. If there is any solution for this then please share with some example code.
I don't think you can do this on the database level.
You would have to do something like this:
Create an array of all country codes (including + sign)
Fetch all the numbers from the database
Use array_map() and in the callback run strpos() against each
element in the country code array and if a match is made remove the
country code from the number
Finally after step 4 is finished run the number array through
array_unique()
CODE:
$country_codes = array('+91', '+61');
$numbers_from_db = array('33445322453', '+913232', '3232', '+614343', '024343');
$sanitized_numbers = array_map(function($number) use ($country_codes){
if(substr($number, 0, 1) === "0") {
$number = substr($number, 1);
return $number;
}
foreach($country_codes as $country_code) {
if(strpos($number, $country_code) !== false) {
$number = str_replace($country_code, "", $number);
return $number;
}
}
return $number;
}, $numbers_from_db);
$distinct_sanitized_numbers = array_unique($sanitized_numbers);
Tested and the out put of var_dump($distinct_sanitized_numbers) is:
array(4) {
[0]=>
string(11) "33445322453"
[1]=>
string(4) "3232"
[3]=>
string(4) "4343"
[4]=>
string(5) "24343"
}
My query does no return anything for my second index. It always sends me a message Notice: Undefined offset: 1. I tried doing with a for it is the same result, so I have read that my problem it is in the query, somebody told me let $stmt be null for freeing resources of my statement. I dont know what is wrong.
These are my methods. I dont know what to someone say use $database->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
Example: $arrayDirectory[] = {'user1', 'user2'};
It must echo 1 2 but just prints me 1
for($i=0;$i<sizeof($arrayDirectory;$i++){
$res[$i] = $obj->obtainID($arrayDirectory[$i]);
echo $res[$i];
}
This is my obtainID method:
public function obtainID($user){
$conexion = $this->objConexion->configuracion();
$query = "CALL sp_xxx('$user')";
$stmt = $conexion->prepare($query);
$stmt->execute();
$resultado = $stmt->fetchColumn();
return $resultado;
}
$stmi = null where?
For one,
$arrayDirectory[] = {'user1', 'user2'};
is a syntax error. { ... } does not work for arrays in PHP. Maybe it's just a typo and you're getting PHP confused with javascsript.
But the bigger issue is the []. That tells PHP to treat $arrayDirectory as an array (fine), but PUSH as a single value whatever you're assigning.
If your code was really:
$arrayDirectory[] = array('user1', 'user2');
This would create the following structure:
array(1) {
[0]=>
array(2) {
[0]=>
string(5) "user1"
[1]=>
string(5) "user2"
}
}
Note that it's a 2-level array. A top level single-element array at index [0]. That element at 0 contains ANOTHER array, which contains your two usernames.
You should have this instead:
$arrayDirectory = array('user1', 'user2');
$res = array();
foreach($arrayDirectory as $user) {
$res[] = $obj->obtainID($user);
}
first of all you are wrong with your function, you forgot to add the ending ')' for sizeof function,also arrays aren't defined with { } you should use array( ) instead.
and finally you are doing a bad practice over there;
you should not call a function in a loop (sizeof()), like this every time the loop goes through it will initiate sizeof() function and it will take some resource, since sizeof($object) won't change while using the loop, you should save it in a variable
$sizeofobject = sizeof($object);
and use that variable in your loop instead