Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Friday, December 30, 2016

How to insert an item into an array at a specific index javascript

var arr = ["X1", "X2", "X3", "X4", "X5"];

Inserting "X2.2" into position "2" without deleting "0" item
arr.splice(2, 0, "X2.2");

First Array Values:
X1,   X2,   X3,   X4,   X5

After insert new value:
X1,   X2,   X2.2,   X3,   X4,   X5

Saturday, January 11, 2014

Using java copy array using copyOf

byte[] src = {1, 2, 3, 4};
byte[] dst = Arrays.copyOf(src, src.length);
System.out.println(Arrays.toString(dst));

Tuesday, October 1, 2013

Grails pagination on a ArrayList

In my recent grails project, i needed to paginate on an array list, so I wrote a function and thought would share it with you all.

public List getFilteredList(int max, int offset) {
    max = Math.min(max ?: 25, 100)
    offset = (offset && offset > 0) ?: 0

    List names = getNames() //Loads the complete list
    int total = names.size()
    int upperLimit = findUpperIndex(offset, max, total)
    List filteredNames = names.getAt(offset..upperLimit)
    return filteredNames
}

private static int findUpperIndex(int offset, int max, int total) {
    max = offset + max - 1
    if (max >= total) {
        max -= max - total + 1
    }
    return max
}
So now if offset=20 and max=10, total = 28 so this will generate a list from 21st to 28th elements of the main list.

Thursday, August 15, 2013

Save PHP Array Data as Formatted XML and Parse Again

<?php 
include 'xml_converter.class.php'; /* Download class file */

include 'xml.class.php';           /* Download class file */
 

/* Your array of data */ 
$data = array(
    
'first_name' => 'Pritom',
    
'middle_name' => "Kumar",
    
'last_name' => 'Mondal',
    
'url' => 'http://pritomkumar.blogspot.com',
    
'languages' => array(
        
'php language !! ' => '<!CDATA[&Php&amp;]]>%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇',
        
'Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨',
        
'Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐',
        
'CSS',
        
"CakePhp<Help]>]]\/\/\/\/\/\/",
        
"jQuery"
    
),
    
'title' => 'Pritom Kumar (Web Developer)',
    
"inline_tag" => "<name><first>Pritom</first><last>Kumar</last></name>",
    
'favorite_blogs' => array(
        
'CSSTricks' => 'http://css-tricks.com',
        
'AJAXian' => 'http://ajaxian.com'
    
),
    
"invalid characters" => array(
        
"''" => "00-&*",
        
"'" => "&#39;",
        
">" => "&#62;",
        
"<" => "&#60;",
        
"&" => "&#38;",
        
"-" => "&#45;",
        
"°" => "&#176;"
    
)
);

 /* Array to xml converting... */ 

$xmlConverter = new XmlConverter($data); 

$xmlString    $xmlConverter->toXmlString();

/* Xml would look like this: */ 
echo $xmlString;


<?xml version="1.0" encoding="UTF-8"?>
<data>
   <first_name><![CDATA[Pritom]]></first_name>
   <middle_name><![CDATA[Kumar]]></middle_name>
   <last_name><![CDATA[Mondal]]></last_name>
   <url><![CDATA[http://pritomkumar.blogspot.com]]></url>
   <languages>
      <php_language____><![CDATA[<!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊⟩⟨ ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇]]></php_language____>
      <tag_0><![CDATA[Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨]]></tag_0>
      <tag_1><![CDATA[Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐]]></tag_1>
      <tag_2><![CDATA[CSS]]></tag_2>
      <tag_3><![CDATA[CakePhp<Help]>]]\/\/\/\/\/\/]]></tag_3>
      <tag_4><![CDATA[jQuery]]></tag_4>
   </languages>
   <title><![CDATA[Pritom Kumar (Web Developer)]]></title>
   <inline_tag><![CDATA[<name><first>Pritom</first><last>Kumar</last></name>]]></inline_tag>
   <favorite_blogs>
      <CSSTricks><![CDATA[http://css-tricks.com]]></CSSTricks>
      <AJAXian><![CDATA[http://ajaxian.com]]></AJAXian>
   </favorite_blogs>
   <invalid_characters>
      <tag___><![CDATA[00-&*]]></tag___>
      <tag__><![CDATA[&#39;]]></tag__>
      <tag__><![CDATA[&#62;]]></tag__>
      <tag__><![CDATA[&#60;]]></tag__>
      <tag__><![CDATA[&#38;]]></tag__>
      <tag__><![CDATA[&#45;]]></tag__>
      <tag___><![CDATA[&#176;]]></tag___>
   </invalid_characters>
</data>


/* After parse xml, array would look like this: */ 

$xmlParser = new XmlToArrayParser($xmlString);

print_r($xmlParser); 

xmlToArrayParser Object
(
    [array] => Array
        (
            [data] => Array
                (
                    [first_name] => Pritom
                    [middle_name] => Kumar
                    [last_name] => Mondal
                    [url] => http://pritomkumar.blogspot.com
                    [languages] => Array
                        (
                            [php_language____] => <!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇
                            [tag_0] => Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨
                            [tag_1] => Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐
                            [tag_2] => CSS
                            [tag_3] => CakePhp<Help]>]]\/\/\/\/\/\/
                            [tag_4] => jQuery
                        )

                    [title] => Pritom Kumar (Web Developer)
                    [inline_tag] => <name><first>Pritom</first><last>Kumar</last></name>
                    [favorite_blogs] => Array
                        (
                            [CSSTricks] => http://css-tricks.com
                            [AJAXian] => http://ajaxian.com
                        )

                    [invalid_characters] => Array
                        (
                            [tag___] => Array
                                (
                                    [0] => 00-&*
                                    [1] => &#176;
                                )

                            [tag__] => Array
                                (
                                    [0] => &#39;
                                    [1] => &#62;
                                    [2] => &#60;
                                    [3] => &#38;
                                    [4] => &#45;
                                )

                        )

                )

        )

    [parse_error] =>
    [parser:xmlToArrayParser:private] => Resource id #4
    [pointer:xmlToArrayParser:private] => Array
        (
            [data] => Array
                (
                    [first_name] => Pritom
                    [middle_name] => Kumar
                    [last_name] => Mondal
                    [url] => http://pritomkumar.blogspot.com
                    [languages] => Array
                        (
                            [php_language____] => <!CDATA[&Php&amp;]]&gt;%♣♠♥♦◊〉〈 ⌋ ⌊ ⌈ ⌉ ⋮ ⋅ ⊥ ⊗ ⊕ ⊇
                            [tag_0] => Java Script ⊆ ⊄ ⊃ ⊂ ≥ ≤ ≡ ≠ ≈ ≅ ∼ ∴ ∫ ∪ ∩ ∨
                            [tag_1] => Java ∧ ∠ ∞ ∝ √ ∗ − ∑ ∏ ∋ ∉ ∈ ∇ ∅ ∃ ∂ ∀ ⇔ ⇓ ⇒ ⇑ ⇐
                            [tag_2] => CSS
                            [tag_3] => CakePhp<Help]>]]\/\/\/\/\/\/
                            [tag_4] => jQuery
                        )

                    [title] => Pritom Kumar (Web Developer)
                    [inline_tag] => <name><first>Pritom</first><last>Kumar</last></name>
                    [favorite_blogs] => Array
                        (
                            [CSSTricks] => http://css-tricks.com
                            [AJAXian] => http://ajaxian.com
                        )

                    [invalid_characters] => Array
                        (
                            [tag___] => Array
                                (
                                    [0] => 00-&*
                                    [1] => &#176;
                                )

                            [tag__] => Array
                                (
                                    [0] => &#39;
                                    [1] => &#62;
                                    [2] => &#60;
                                    [3] => &#38;
                                    [4] => &#45;
                                )

                        )

                )

        )

)


?>

Wednesday, July 17, 2013

PHP: Recursively convert an object to an array

When pulling in array from outside data sources you often receive an array back. The problem is that sometimes even though you know you should have an array your application does not and therefore assigns it to the stdObject object, which of course is nothing. To make it usable you must convert it back into an array. With a simple object that may be as simple as a cast, but when you are working with large complex datasets that may be several layers deep you need to make sure you get at all of them. Enter beautiful recursion. After playing with PHPs array_walk_recursive() for a bit I hit on a custom recursive function that does exactly the job. Simply pass it your object and it will munch away at it trying to convert it into a PHP array. Take a gander at the code for this below.
<?php 
function object_to_array($obj)
{
    if (
is_object($obj)) {
        
$obj = (array) $obj;
    }
    if (
is_array($obj)) {
        
$new = array();
        foreach (
$obj as $key => $val) {
            
$new[$key] = object_to_array($val);
        }
    } else {
        
$new $obj;
    }
    return 
$new;
}
?>

http://ben.lobaugh.net/blog/567/php-recursively-convert-an-object-to-an-array

Wednesday, June 19, 2013

bash split string into array

IFS=', ' read -a array <<< "$string" /* array is the variable name */
To access an individual element:
echo "${array[0]}"
To iterate over the elements:
for element in "${array[@]}"
do
    echo "$element"
done
To get both the index and the value:
for index in "${!array[@]}"
do
    echo "$index ${array[index]}"
done
The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.
unset "array[1]"
array[42]=Earth

Monday, June 3, 2013

jQuery delete a given key from array

When I have an array like this:
  1. var test = Array();
  2. test['key1'] = 'value1';
  3. test['key2'] = 'value2';
I believe the delete operator in JavaScript will solve this:
  1. var test = new Array();
  2. test['key1'] = 'value1';
  3. test['key2'] = 'value2';
  4. delete test['key1']; // will remove key1 from the array

Monday, April 29, 2013

Create and download csv file from array using php


Create and download csv file from array using php.
<?php
function arrayToCsv( array $fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $outputString = "";
    foreach($fields as $tempFields) {
        $output = array();
        foreach ( $tempFields as $field ) {
            if ($field === null && $nullToMysqlNull) {
                $output[] = "NULL";
                continue;
            }

            // Enclose fields containing $delimiter, $enclosure or whitespace
            if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
                $output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure;
            }
            else {
                $output[] = $field;
            }
        }
        $outputString .= implode( $delimiter, $output )."\n";
    }
    return $outputString;
}
?>
Use:
<?php
$dataArray = array();
array_push($dataArray, array(
    "First Name",
    "Last Name",
    "Number",
    "Group"
));
foreach($dataList as $index => $data) {
    array_push($dataArray, array(
        "".$data["first_name"],
        "".$data["last_name"],
        "".$data["mobile_number"],
        "".$data["group_name"]
    ));
}
$csvString = arrayToCsv($dataArray);
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=list.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $csvString;
?>

Php check a value exists in multi level array and return path

Search in array using php by value if the array is any depth data.
<?php
function array_value_exists($search = "", $searchArray = array(), $returnKey = false, &$returnKeyArray = array(), $level = 0) {
    $returnValue = false;
    $search = trim(strval($search));
    if(strlen($search) == 0) {
        return false;
    }
    if(is_null($searchArray)) {
        return false;
    }
    if(!is_array($searchArray)) {
        return false;
    }
    foreach($searchArray as $key => $value) {
        array_push($returnKeyArray, $key);
        if(is_string($value)) {
            if($search == trim($value)) {
                $returnValue = true;
                break;
            }
        } else if(is_array($value)) {
            $returnValue = array_value_exists($search, $value, false, $returnKeyArray);
            if($returnValue == true) {
                break;
            }
        }
    }
    if($returnKey == true) {
        return $returnKeyArray;
    }
    return $returnValue;
}
?>

Use:<?php
$ary = array(
            "bm" => array(
                "dev" => array(
                    "pritom" => array(
                        "email" => "pritomkucse@yahoo.com"
                    ),
                    "touhid" => array(
                        "email" => "touhid@yahoo.com"
                    )
                ),
                "designer" => array(
                    "dipu" => array(
                        "email" => "dipu@yahoo.com"
                    )
                )
            ),
            "gpit" => array(
                "dev" => array(
                    "sanat" => array(
                        "email" => "sanat@gpit.com"
                    )
                )
            )
        );
        $has = array_value_exists("pritomkucse@yahoo.com", $ary);
        echo $has == true ? "True" : "False";
        print_r(array_value_exists("pritomkucse@yahoo.com", $ary, true));
?>

Output:
1. True (Find or not)
2. Path to this value.
Array
(
    [0] => bm
    [1] => dev
    [2] => pritom
    [3] => email
)