Recent Posts

Showing posts with label convert. Show all posts
Showing posts with label convert. Show all posts

Convert PHP Array in JavaScript Array

This is the way you can convert this PHP Array:

Array
(
    [0] => 001-1234567
    [1] => 1234567
    [2] => 12345678
    [3] => 12345678
    [4] => 12345678
    [5] => AP1W3242
    [6] => AP7X1234
    [7] => AS1234
    [8] => MH9Z2324
    [9] => MX1234
    [10] => TN1A3242
    [11] => ZZ1234
)
To this in JavaScript:

var cities = [
    "Aberdeen",
    "Ada",
    "Adamsville",
    "Addyston",
    "Adelphi",
    "Adena",
    "Adrian",
    "Akron",
    "Albany"
];
If you don't have PHP 5.2 you can use something like this:
function js_str($s)
{
    return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}

function js_array($array)
{
    $temp = array_map('js_str', $array);
    return '[' . implode(',', $temp) . ']';
}

echo 'var cities = ', js_array($php_cities_array), ';';

How to: convert one date format to another (PHP)

The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.

You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.

PHP 5.3 and up

Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.

PHP 5.2 and lower

You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.

But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:

$old_date = date('l, F d y h:i:s');              // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);