...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
July 4, 2013

How to merge array and preserve keys?

Joe’s Question:

I have two arrays:

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);

I want to merge them and keep the keys and the order and not re-index!!

How to get like this?

Array
(
    [a] => new value
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

I try to array_merge() but it will not be preserved the keys:

print_r(array_merge($array1, $array2));

Array
(
    [a] => 'new value'
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [0] => 456
)

I try to the union operator but it will not overwriting that element:

print_r($array1 + $array2);

Array
(
    [a] => 1   <-- not overwriting
    [b] => 2
    [c] => 3
    [d] => 4
    [e] => 5
    [f] => 6
    [123] => 456
)

I try to swapped place but the order is wrong, not my need:

print_r($array2 + $array1);

Array
(
    [d] => 4
    [e] => 5
    [f] => 6
    [a] => new value 
    [123] => 456
    [b] => 2
    [c] => 3
)

I dont want to use a loop, is there a way for high performance?

You’re looking for array_replace():

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);
print_r(array_replace($array1, $array2));

Available since PHP 5.3.

Update

You can also use the union array operator; it works for older versions and might actually be faster too:

print_r($array2 + $array1);

array_replace_recursive() or array_replace() is the function you are looking for

$array1 = array('a' => 1, 'b' => 2, 'c' => 3);
$array2 = array('d' => 4, 'e' => 5, 'f' => 6, 'a' => 'new value', '123' => 456);


var_dump(array_replace_recursive($array1, $array2));

Demo

Read more

MySQL Convert Numbers to Alphabets

User1258600’s Question:

I have an auto-increment transactionID type=MEDIUMINT(9) in my table. I want to also display a unique 4-character (which can grow over time, but 4 for now) alphabetical Redemption Code to my users. What is the best way to derive this alphabetical code from my transactionID, preferably straight from the SELECT statement?

Thank you. 🙂

That mostly depends on what alphabet you want to use.

You may use TO_BASE64 to convert it it to base64 encoded string or simply do something like:

select REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
REPLACE(your_number, '0', 'A')
, '1', 'B')
, '2', 'C')
, '3', 'D')
, '4', 'E')
, '5', 'F')
, '6', 'G')
, '7', 'H')
, '8', 'I')
, '9', 'J')

if you want custom alphabet.

In case you want something shorter, you can go a slightly harder way:

You use 9-digit decimal (maximum 999999999), which translates to 8 hex digits (0x3B9AC9FF), i.e. 4 bytes. What you can do is divide your number in 4 binary octets, convert them to chars, construct new string and feed it to TO_BASE64():

select TO_BASE64(CONCAT(CHAR(FLOOR(your_number/(256*256*256))%256),CHAR(FLOOR(your_number/(256*256))%256),CHAR(FLOOR(your_number/256)%256),CHAR(your_number%256)))

Note, that TO_BASE64() function is available only in MySQL 5.6 on-wards.

Now, for those on older versions – we don’t want to implement base64 encoding with our bare hands, don’t we? So, lets go the easier way: we have 30 bits in those 9 decimal digits, which would be 30/6=5 characters, if we use 64 continuous character alphabet after CHAR(32), which is space, which we don’t want to use:

SELECT CONCAT(`enter code here`CHAR(FLOOR(your_number/(64*64*64*64))%64+33),CHAR(FLOOR(your_number/(64*64*64))%64+33),CHAR(FLOOR(your_number/(64*64))%64+33),CHAR(FLOOR(your_number/64)%64+64),CHAR(your_number%64+33))

You can generate a hash with the value of transaction id.

Like:

SELECT MD5(transactionID) FROM `yourtable`;

There are several other types of similar functions you can use.

Read more

Style display:none not working in IE8, IE9, IE10 Compatibility View

Sukhminder Singh’s Question:

I have two DIVs on my page. One of them is set to display:none based on some condition. It works well on IE10, Firefox and Chrome. But it does not work on IE8, IE9 and IE10 Compatibility View. As a result, it shows both of the DIVs. Can someone suggest what to do to fix this issue?

<div id="dv1" style="background: url(http://abc.com/images/green.gif) no-repeat scroll 0px 0px transparent; height: 26px; width: 171px; display: none;"></div>


<div id="dv2" style="background:url(http://abc.com/images/red.gif) no-repeat scroll 0 0 transparent;height:26px; width:142px; padding-left:18px;padding-right:11px;"/>

You forgot to put </div> for both divs.

I think you want something like below.

<div id="dv1" style="background: url(http://abc.com/images/green.gif) no-repeat scroll 0px 0px transparent; height: 26px; width: 171px; display: none;"></div>

<div id="dv2" style="background:url(http://abc.com/images/red.gif) no-repeat scroll 0 0 transparent;height:26px; width:142px; padding-left:18px;padding-right:11px;"></div>

Check the demo, it works fine in all browsers.

<div> is not a self closing tag. You cannot end this tag by writing it as <div .... /> at the end. They are container tag and they should contain some element for display: none to work.

For example:

<div style="display: none;">
     What ever inside will never show
</div>

Make these changes and it will work as you want.

Read more
July 2, 2013

htaccess rule cannot override previous rule

MrN’s Question:

I have a bunch of htaccess rule setup on website.

RewriteEngine On
RewriteBase /
RewriteRule ^google73947f9bfca52abe.html$    google73947f9bfca52abe.html [L]
RewriteRule ^page/(.*)$ index.php?title=page&r=$1 [L]
RewriteRule ^media/(.*)$ index.php?title=page&r=$1 [L]

RewriteRule ^admin/$    admin/php [L]
RewriteRule ^index.html$    index.php [L]
RewriteRule ^crons/$    crons/ [L]

#I did this to forward request to directory    
RewriteRule ^sites/$    sites/ [L]

#This  is the rule creating problem
#RewriteRule ^sites/([^.]+)$    sites/$1 [L]


RewriteRule ^([^.]+).html$   /index.php?title=$1
RewriteRule ^(.*).htm       index.php?action=$1 [L]RewriteRule ^([^.]+)$   /index.php?title=$1

I want to override every rule for those that start with site.com/sites to go the directory instead of going to index.php as it configured to do so.

Whenever I go to site.com/sites the sites takes me to site.com/site/?title=sites but I can still browse it as folder but Whenever I open a html file like lets say test.html it takes me directly to index.php on earlier directory as it is suppose to.

How to write rule which lets me browse a directly freely?

You have to configure to omit all the rules when the line sites is encountered.

Here is your solution:

RewriteEngine On
RewriteRule ^(sites) - [L]

#Rest of your rules
Read more
July 1, 2013

$('body').click function is working before Datepicker (jquery) beforeShow method

Dmlcskn’s Question:

$(‘body’).click function is working before Datepicker (jquery) beforeShow method.
How can I trigger first onselect method of Datepicker (jquery). I mean

   $('body').click(function (evt) {

    // do something
    }

 $('#UxDatePickerFrom').datetimepicker({

beforeShow: function (inst) {
                // do something on select
            })

but if I select datepicker , body click is working first which is unwanted.

$('body').click(); is a global click handler for all the elements with it, so where ever you click on the body or on the date picker the function will execute.

Your solution is to change the click handler to affect more specialized group of elements and not all of it.

$("#yourspecificelement").click(function() {
    // ....
});
Read more
June 29, 2013

Ajax response error

TNK’s Question:

I need to make a mysql query according to the value of dropdown list. Here I use ajax to send dropdown value to the server. I think this part is working for me. But problem is I can not get it to php. Note: both are in the same page.

This is my Jquery code :

$('#filter-value').change(function(){
    var filterValue = $(this).val();
    //console.log(filterValue); 

    $.ajax({
        type: 'post',
        dataType: 'html',
        data: {filter: filterValue},
        success:function(data){ 
            alert(data); 
        }, 
        error:function (xhr, ajaxOptions, thrownError){
            //On error, we alert user
            alert(thrownError);
        }, 
        complete: function(){
            //alert('update success'); 
        }
    });
});

This is HTML form

    <form method="post" action="">
        <select id="filter-value" name="filter">
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="30">30</option>              
        </select>
    </form>

This is my PHP code that I am trying on the top of the page :

if (isset($_POST['filter'])) {
    $filter = $_POST['filter']; 
    echo $filter; 
    exit;
} else {
    echo 'bad';
}

But this php code is always going to else part and print ‘bad’

Can anybody tell me where I am going wrong?

Thank you.

You have missed to specify the URL of the script. Be ensure that you are querying the correct file from the AJAX.

$.ajax({
    type: 'post',
    url: 'yourpage.php', // This one 
    //.....
});
Read more

Unsort in array

Alex’s Question:

Good day.

I would be like get 3 keys from $arr where value $arN[0] will be more than other…

Code:

$ar1=array(201,281);
$ar2=array(1252760,1359724);
$ar3=array(452760,34349724);
$ar4=array(1260,134344);
$ar5=array(232750,1359724);
$ar6=array(60,1439724);

$arr[]=array(6299927 => $ar1);
$arr[]=array(1252760 => $ar2);
$arr[]=array(3432444 => $ar3);
$arr[]=array(3435543 => $ar4);
$arr[]=array(7645466 => $ar5);
$arr[]=array(4574534 => $ar6);

Next function sorting array $a descending:

function cmp($a, $b)
{
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? 1 : -1;
}

$a = array(3, 2, 5, 6, 1);

usort($, "cmp");

foreach ($a as $key => $value) {
    echo "$key: $valuen";
}
outpoot: 0:6 1:5 2:4 3:2 4:1

But how change this function for my example(for my big array)?

Tell me please how make this?

How write right?

Very confusing but I think you are looking for something like this. It will give you the index of the array whose first item is greater than the first item in the next array.

foreach($arr as $key => $array) {
    if($array[0] > $arr[$key+1][0]) {
       echo $key;
    }
}
Read more
June 27, 2013

PHP: header alternative?

Ralph’s Question:

I wanted to know if the echoing the following would be a good alternative to using header(“Location: index.html”) without having to use output_buffering

echo "<script type='text/javascript>window.location = 'index.html';</script>";

There are times I would like to redirect possibly in a body, would the above work fine or is it worth turning on the output_buffering option and just user header()?

header() defines the page the user is viewing. Using output buffering forces to ignore the previous output buffer, so it is not considered an efficient way to redirect. So, here are my suggestions:

  1. If your only target is to redirect, then make sure you output nothing before header statement executes. In this case header is appropriate.

  2. If you need to show your page and based on user interactivity need to redirect to the different page, use the JavaScript Redirection.

Read more
June 25, 2013

Java: silly newbie issue about path used in import statement

Ggkmath’s Question:

I’m working through the example here:

http://www.vogella.com/articles/JavaPDF/article.html

In my file, I’ve got:

package com.mycompanyname.mydirectory;

import com.mycompanyname.OneOfMyClasses;
import com.itextpdf.text.Document;
...

 public class MyClass {
     ...
 }

Everything is working fine. What I don’t understand is that since I just copied the import statement directly from the link above for the iText portion — why does com.itextpdf.text.Document work?

I mean, if I look in directory com.mycompanyname I can see OneOfMyClasses.java there.

But in the com directly, there is no itextpdf directory (although maybe my user doesn’t have permission to see it(?)).

Hoping someone can help me understand what I’m missing here. Doesn’t the import point to a specific directory that I should be able to see the class? Is there a different com directory somewhere that iText is using, and com.itextpdf.text points to there? (if so, where’s the directory located)?

I installed the jar file for iText in the lib folder as per usual, and made sure it was included in the classpath.

Those classes are inside a JAR file that is added to the classpath:

Create a new Java project “de.vogella.itext.write” with the package “de.vogella.itext.write”. Create a folder “lib” and put the iText library (jar file) into this folder. Add the jar to your classpath.

import statements will look inside whatever directory trees are in the classpath, which includes the current directory at compilation time (tipically the src/ directory in your project) as well as any directory specified through environment variable or JVM startup parameter. See this about the classpath.

EDIT

You do need the imports whenever you use classes across packages. Every public class/interface you define is in a package. If whatever you are referencing belongs to another package, you need to import it.

JARs are zip files that contain directories and files inside. It’s the same as plain directories and files, only packed.

That class is most probably imported in a JAR library. Inside such JAR file, the class files are kept in exact package/folder structure as you use when importing them.

Read more
June 24, 2013

PHP: sending email with my website domain

Abdullah Salma’s Question:

When I used mail() function and sent an email to my self from my website. I recived the email from myusername@pickens.dreamhost.com I want to change the sender into noreply@mydomain.com

but is there a way ?

You can change the sender by using headers while sending your email. Such basic things are well illustrated on the PHP manual page of mail()

This is an example taken from that manual page

$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "rn" . 
            // ^ This is where you update your header to show the sender
    'Reply-To: webmaster@example.com' . "rn" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
Read more
...

Please fill the form - I will response as fast as I can!