PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

array_change_key_case> <rename_function
Last updated: Sun, 25 Nov 2007

view this page in

배열함수

소개

이 함수는 다양한 방법으로 배열에 접근하고 배열을 조작할 수 있게 해 준다. 배열은 변수들의 집합을 저장, 관리, 처리하는데 있어서 핵심적이다.

일차원 뿐만 아니라 다차원 배열이 지원되고 있고, 사용자나 다른 함수에 의해 생성될 수 있다. 데이터베이스 질의문으로부터 배열을 생성하는 전용 데이터베이스 제어 함수와 배열을 반환하는 함수를 제공한다.

PHP에서의 배열 구현과 사용법에 대한 자세한 설명은 매뉴얼의 배열 섹션을 참고.

요구 조건

이 확장을 빌드할 때 외부 라이브러리가 필요하지 않습니다.

설치

이 함수들은 설치하지 않아도 사용할 수 있습니다; PHP 코어의 일부입니다.

실행시 설정

이 확장은 php.ini 설정이 존재하지 않습니다.

자원형

이 확장은 리소스형을 정의하지 않습니다.

예약 상수

아래 상수들은 PHP 코어의 일부로, 항상 사용할 수 있습니다.

CASE_LOWER (integer)
CASE_LOWERarray_change_key_case() 함수에서 배열 키를 소문자로 변환하는데 사용된다. 또한 이 상수는 array_change_key_case()의 기본값이다.
CASE_UPPER (integer)
CASE_UPPERarray_change_key_case() 함수에서 배열 키를 대문자로 변환하는데 사용된다.

정렬 순서 플래그:

SORT_ASC (integer)
SORT_ASCarray_multisort() 함수에서 오름차순 정렬에 사용된다.
SORT_DESC (integer)
SORT_DESCarray_multisort() 함수에서 내림차순 정렬에 사용된다.

정렬 형태 플래그: 여러 정렬함수에 의해 사용됨.

SORT_REGULAR (integer)
SORT_REGULAR는 아이템들을 통상적인 방법으로 비교하는데 사용됨.
SORT_NUMERIC (integer)
SORT_NUMERIC는 아이템들을 수치로서 비교하는데 사용됨.
SORT_STRING (integer)
SORT_STRING는 아이템들을 문자열로서 비교하는데 사용됨.

COUNT_NORMAL (integer)
COUNT_RECURSIVE (integer)
EXTR_OVERWRITE (integer)
EXTR_SKIP (integer)
EXTR_PREFIX_SAME (integer)
EXTR_PREFIX_ALL (integer)
EXTR_PREFIX_INVALID (integer)
EXTR_PREFIX_IF_EXISTS (integer)
EXTR_IF_EXISTS (integer)
EXTR_REFS (integer)

Table of Contents

  • array_change_key_case — 모두 대문자나 소문자화된 문자열 키를 갖는 배열로 반환한다
  • array_chunk — 배열을 여러 덩어리로 분산시킨다
  • array_combine — 키를 위한 배열과 값을 위한 배열을 각각 사용하여 배열을 생성한다
  • array_count_values — 배열 값의 수를 센다
  • array_diff_assoc — 인덱스 검사와 함께 배열간의 차이를 계산한다
  • array_diff_key — Computes the difference of arrays using keys for comparison
  • array_diff_uassoc — Computes the difference of arrays with additional index check which is performed by a user supplied callback function
  • array_diff_ukey — Computes the difference of arrays using a callback function on the keys for comparison
  • array_diff — 배열간의 차이를 계산한다
  • array_fill_keys — Fill an array with values, specifying keys
  • array_fill — 배열을 특정값으로 채운다
  • array_filter — 콜백함수를 사용하여 배열의 원소를 필터한다
  • array_flip — 배열안의 모든 키를 각 키의 연관값으로 바꾼다.
  • array_intersect_assoc — 인덱스 검사과 함께 배열의 중복을 계산한다
  • array_intersect_key — Computes the intersection of arrays using keys for comparison
  • array_intersect_uassoc — Computes the intersection of arrays with additional index check, compares indexes by a callback function
  • array_intersect_ukey — Computes the intersection of arrays using a callback function on the keys for comparison
  • array_intersect — 배열의 중복을 계산한다
  • array_key_exists — 주어진 키와 인덱스가 배열에 존재하는지 확인한다
  • array_keys — 배열의 모든 키를 반환한다
  • array_map — Applies the callback to the elements of the given arrays
  • array_merge_recursive — 두개 이상의 배열을 재귀적으로 병합한다
  • array_merge — 두개 이상의 배열을 병합한다
  • array_multisort — 여러개의 배열 또는 다차원 배열을 정렬한다
  • array_pad — 설정된 길이만큼 특정 값으로 배열을 채운다
  • array_pop — 배열 끝의 요소를 뽑아낸다
  • array_product — Calculate the product of values in an array
  • array_push — 배열의 끝에 하나 이상의 원소를 넣는다.
  • array_rand — 배열안에서 하나 이상의 임의 원소를 뽑아낸다
  • array_reduce — 콜백 함수를 사용하여 배열을 반복적으로 단일 값으로 축소시킨다
  • array_reverse — 배열 원소를 역순으로 반환한다
  • array_search — 배열에서 주어진 값을 검색하고 성공하면 해당 키를 반환한다
  • array_shift — 배열의 맨 앞에 있는 원소를 옆으로 이동시킨다
  • array_slice — 배열의 일부를 추출한다
  • array_splice — 배열의 일부를 삭제하고, 그 위치에 다른 내용을 대체한다
  • array_sum — 배열내의 값들의 합을 계산한다
  • array_udiff_assoc — Computes the difference of arrays with additional index check, compares data by a callback function
  • array_udiff_uassoc — Computes the difference of arrays with additional index check, compares data and indexes by a callback function
  • array_udiff — Computes the difference of arrays by using a callback function for data comparison
  • array_uintersect_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function
  • array_uintersect_uassoc — Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
  • array_uintersect — Computes the intersection of arrays, compares data by a callback function
  • array_unique — 배열에서 중복된 값을 제거한다
  • array_unshift — 배열의 맨 앞에 하나 이상의 원소를 첨가한다
  • array_values — 배열의 모든 값들을 반환한다
  • array_walk_recursive — Apply a user function recursively to every member of an array
  • array_walk — 배열의 개개의 원소에 대해서 특정 함수를 적용하여 수행한다
  • array — 배열을 생성한다
  • arsort — 배열을 내림차순 정렬하고 인덱스의 상관관계를 유지한다.
  • asort — 배열을 정렬하고 인덱스 상관 관계를 유지한다
  • compact — 여러 변수들과 값을 갖는 배열을 생성한다
  • count — 배열의 원소수, 객체의 프로퍼티수를 셉니다
  • current — 배열의 현재 원소를 반환한다
  • each — 배열에서 현재의 키와 값 쌍을 반환하고 배열 커서를 전진시킨다
  • end — 내부 배열 포인터를 마지막 원소를 가리키게 한다
  • extract — 배열의 현재 심볼 테이블로 변수들을 입력한다
  • in_array — 배열에서 값이 존재하는지 점검한다
  • key — 연관배열에서 키를 꺼낸다
  • krsort — 역순으로 키에 의해 배열을 정렬한다
  • ksort — 키에 의해 배열을 정렬한다
  • list — 배열처럼 변수들을 지정한다
  • natcasesort — 대소문자를 구별하지 않고 "natural order" 알고리즘을 사용하여 배열을 정렬한다
  • natsort — "natural order" 알고리즘을 사용하여 배열을 정렬한다
  • next — 배열의 내부 배열 포인터를 전진시킨다
  • pos — 배열에서 현재 원소를 꺼내온다
  • prev — 내부 배열 포인터를 앞으로 돌린다
  • range — 특정 범위의 원소를 갖는 배열을 생성한다
  • reset — 배열의 내부 포인터가 배열의 첫번째 원소를 가리키게 한다
  • rsort — 역순으로 배열을 정렬한다
  • shuffle — 배열을 뒤섞는다
  • sizeof — count의 별칭
  • sort — 배열을 정렬한다
  • uasort — 사용자-정의 비교함수로 배열을 정렬하고 인덱스 연관성을 유지한다
  • uksort — 사용자-정의된 비교함수를 사용하여 키에 의해 배열을 정렬한다
  • usort — 사용자-정의된 비교함수를 사용하여 값들에 의해 배열을 정렬한다


array_change_key_case> <rename_function
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
배열
pragash_jey at yahoo dot com
06-Apr-2008 11:38
Java Like Array Implementation!

<?php
/*
 * Author : Pragash Jeyaratnam
 * Vector Class
 * PHP Version 5.2.5
 * Contact : pragash_jey@yahoo.com.
 */
class Vector
{
   
/*
     * The number of valid components in this Vector object.
     */
   
protected $elementCount;
   
/*
     * The array buffer into which the components of the vector are stored.
     */
   
protected $elementData;
   
   
         
   
/**Default vector Constructor*/
   
function __construct()
    {
       
$this->elementData = array();
       
$this->elementCount = count($this->elementData);
    }
   
   
   
   
/**Append the parameter element to the vector*/
   
public function add($object)
    {
        if(!empty(
$object))
        {
           
$this->elementData[] = $object;
           
$this->elementCount = count($this->elementData);
            return
true;
        }
        else
            return
false;
           
    }
   
   
/*
     * Returns true of Vector is empty false otherwise
     */
   
public function isEmpty()
    {
        return(
$this->elementCount==0);
    }
   
   
 
/*
   * Returns the current size of this Vector
   */
  
public function size()
   {
       return
$this->elementCount;
   }
   
  
/*
    *  Searches for the first occurence of the given argument
    **/
  
public function indexOf($object)
   {
          if((
$index =array_search($object,$this->elementData)) !==false)
              return
$index;
          else
              return -
1;
   }
  
  
/*
    * This function will retain TRUE if $object is contained
    * within the vector else FALSE
    */
  
  
public function contains($object)
   {
           return (
$this->indexOf($object)>=0);
   }
   
  
/*
    * Returns Vector Object at index $index
    * Error : Null is returned
    */
     
  
public function get($index)
   {
           if(
$this->checkBound($index))
           {
               return (
$this->elementData[$index]);
           }
           return
NULL;
   }
  
  
/*
    * Sets the object at $index to be $object
    **/
  
  
public function set($index,$object)
   {
           if(
$this->checkBound($index))
           {
              
$this->elementData[$index] =$object ;
               return
true;
           }
           return
false;
   }
  
 
/*
   * Removes element at $index
   **/
  
     
public function removeAt($index)
      {
       if (
$this->checkBound($index))
           {
                 for (
$i = $index; $i != $this->elementCount - 1; $i++)
                  {
                  
$this->elementData[$i] = $this->elementData[$i +1];
             }
      
array_pop($this->elementData);
      
$this->elementCount = count($this->elementData);
           
       return
true;
       }
       else {
            return
false;
            }
      }
   
   
/**
     * Removes all elements from the Vector.  Note that this does not
     * resize the internal data array.
     */
  
public function removeAll()
   {
         if(
$this->elementCount ==0)
             return;
         for(
$i=0;$i<$this->size();$i++)
         {
            
$this->set($i,NULL);
         }
   }
   
   
  
/*
    * This function checks whether index
    * is within the array bound
    **/
  
  
private function checkBound($index)
   {
         if(
$index > $this->elementCount-1 || $index < 0)
         {
            
throw new Exception('Array Index Out Of Bound Exception');
             return
false;
         }
         return
true;
   }
  
   
/*
     *Removes the first element from the Vector
     */
   
   
public function removeFirstElement()
    {
        if(
$this->elementCount==0)
        {
           
throw new Exception('No Such Element');
        }
       
$test =array_shift($this->elementData);
        if(!empty(
$test))
           
$this->elementCount = count($this->elementData);
    }
  
}
?>
Anonymous
30-Mar-2008 04:28
This is the shorter way to flatten a array:
<?php
 
function array_flatten($a) {
    foreach(
$a as $k=>$v) $a[$k]=(array)$v;
    return
call_user_func_array(array_merge,$a);
  }
?>
bas at muer dot nl
18-Mar-2008 01:17
I see a lot of people here writing complex functions to convert an array to a string, for use with Javascript or other things (possibly even databases, which would be bad).
For Javascript, the most efficient way would be JSON (http://www.php.net/json_encode). For normal use, serialize() (http://www.php.net/serialize) is your friend.
jake at blah dot inf
07-Mar-2008 11:03
@margol:

<?php
$tuple_array
= array(array('key1' => 'val1'), array('key2' => 'val2'));
list(
$key, $val) = each(array_pop($tuple_array));
?>

But, why not use a two element array instead of a single-element associative array?

<?php
$tuple_array
= array(array('key1', 'val1'), array('key2','val2'));
list(
$key,$val) = array_pop($tuple_array);
?>
margol at beamartyr dot net
04-Mar-2008 06:45
More intuitive tuple support would be nice  :)

But for those scratching their heads, like I did, to extract a tuple from an array of tuples, do something like:

    $tuple = array_pop($tuple_array);
    $key = key($tuple);
    $val = $tuple[$key];
yousefomar (a) yahoo dot com
29-Feb-2008 04:26
Here is how you refresh the expiration time for multiple cookies:

// get the cookie names
$keys=array_keys($_COOKIE);

// loop through all the cookies and update the exp. time
for ($i=0; $i<count($_COOKIE);$i++)
   setcookie( $keys[$i], $_COOKIE[$keys[$i]], time()+3600);

you can use this in authentication validate file to keep the session up.
ms419 at freezone dot co dot uk
15-Feb-2008 03:35
This function takes an array, a key and a value. If the key is not an array, it acts just like $array[$key] =& $value; If the key is an array, it recurses in the array, creating nested arrays as necessary.

Example:

$array = array('A' => array('B' => 'phi'));
$key = array('A', 'Z');
$value = 'gamma';

arraySet($array, $key, $value);

$array should now be:

array('A' => array('B' => 'phi', 'C' => 'gamma'));

This is useful for constructing nested arrays from sets of filesystem paths (e.g. 'A/B/C') or structured variable names (e.g. 'A.B.C' or 'A[B][C]')

Example:

arraySet($array, preg_split('/\//', $path, -1, PREG_SPLIT_NO_EMPTY), $value);

function arraySet(array &$array, $key, &$value)
{
    if (is_array($key)) {
        $keyComponent = array_shift($key);

        if (empty($key)) {
            $array[$keyComponent] =& $value;
            return;
        }

        if (!is_array($array[$keyComponent])) {
            $array[$keyComponent] = array();
        }

        PHP_CodeSniffer_arraySet($array[$keyComponent], $key, $value);
        return;
    }

    $array[$key] =& $value;
}
dennis at DONTSPAMME dot born05 dot nl
14-Feb-2008 12:22
I haven't completely figured out when or why an array gets referenced or copied, but it gave me quite the headache..

So i wrote a function which recursively copies an array while preserving keys and also clones objects if encountered

<?php
   
/**
     * make a recursive copy of an array
     *
     * @param array $aSource
     * @return array    copy of source array
     */
   
function array_copy ($aSource) {
       
// check if input is really an array
       
if (!is_array($aSource)) {
           
throw new Exception("Input is not an Array");
        }
       
       
// initialize return array
       
$aRetAr = array();
       
       
// get array keys
       
$aKeys = array_keys($aSource);
       
// get array values
       
$aVals = array_values($aSource);
       
       
// loop through array and assign keys+values to new return array
       
for ($x=0;$x<count($aKeys);$x++) {
           
// clone if object
           
if (is_object($aVals[$x])) {
               
$aRetAr[$aKeys[$x]]=clone $aVals[$x];
           
// recursively add array
           
} elseif (is_array($aVals[$x])) {
               
$aRetAr[$aKeys[$x]]=array_copy ($aVals[$x]);
           
// assign just a plain scalar value
           
} else {
               
$aRetAr[$aKeys[$x]]=$aVals[$x];
            }
        }
       
        return
$aRetAr;
    }
?>

I hope i can save someone else's aspirine with this ;)
csorfab at gmail dot com
06-Feb-2008 03:26
Here's a function I wrote to combine the values in an array in all different ways, and which returns a two-dimensional array as a byref result.

E.g.

if called:
comb(array(1, 2, 3), $r);

then $r would be:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

<?php

   
function comb($arr, &$rarr, $vtemp = array()){   
        foreach(
$arr as $key => $value){
           
$vtemp2 = $vtemp;
           
$vtemp2[] = $value;

           
$atemp = $arr;           
            unset(
$atemp[$key]);
           
            if(
count($atemp) > 0){
               
comb($atemp, $rarr, $vtemp2);
            } else {
               
$t = array();
           
                foreach(
$vtemp2 as $val){
                   
$t[] = $val;
                }
               
               
$rarr[] = $t;
            }
        }
    }

?>
christian dot reinecke at web dot de
03-Feb-2008 06:12
Here are two more functions handling string2array and access array by string. It's useful if you want to access an array in xpath-style, such as parse_ini_file return values with $process_sections = TRUE.

<?php
function createArrayByString($string, $separator, $value = NULL)
{
    if (
strlen($string) > 0) {
       
$splitter = explode($separator, $string);
       
$index = array_shift($splitter); // get first element
       
$function = __FUNCTION__;
        return array(
$index => $function(implode($separator, $splitter), $separator, $value));
    }
    return
$value;
}

function
accessArrayByString($array, $string, $separator, $default = NULL)
{
    if (!
is_array($array)) {
        return empty(
$string) ? $array : $default;
    }
    @list (
$key, $rest) = explode($separator, $string, 2); // @ needed for last access
   
   
$function = __FUNCTION__;
    return
array_key_exists($key, $array)
         ?
$function($array[$key], $rest, $separator, $default)
         :
$default;
}

$string = "one.two.three.four";
$separator = ".";

$array = createArrayByString($string, $separator, "standard value");
$return = accessArrayByString($array, $string, $separator, "element not found");

var_dump($array); // should return array("one" => array("two" => array("three" => array("four" => "standard value"))))
var_dump($return); // should return "standard value";
?>

change the function name to what ever you want, the recursive call uses __FUNCTION__ for re-call.
florian at egliselasauzaie dot fr
30-Jan-2008 07:09
I've created a class which is comparable to a Vector in C++;
<?php
class Vector {
   
public $nb_elements;
   
public $liste;

   
public function Vector() {
       
$this->liste = array ();
       
$this->nb_elements = count($this->liste);
    }

   
public function push_back($valeur) {
        if (!empty (
$valeur)) {
           
$this->liste[] = $valeur;
           
$this->nb_elements = count($this->liste);
            return
true;
        } else {
            return
false;
        }
    }
   
public function insert_at($indice, $valeur) {
        if (
$indice > 0 && $indice < $this->nb_elements) {
            for (
$i = $this->nb_elements; $i != $indice; $i--) {
               
$this->liste[$i] = $this->liste[$i -1];
            }
           
$this->liste[$indice] = $valeur;
           
$this->nb_elements = count($this->liste);
            return
true;
        } else {
            return
false;
        }
    }
   
public function remove_at($indice) {
        if (
$indice > 0 && $indice < $this->nb_elements) {
            for (
$i = $indice; $i != $this->nb_elements - 1; $i++) {
               
$this->liste[$i] = $this->liste[$i +1];
            }
           
array_pop($this->liste);
           
$this->nb_elements = count($this->liste);
            return
true;
        } else {
            return
false;
        }
    }
   
public function pop() {
       
$value = array_pop($this->liste);
       
$this->nb_elements = count($this->liste);
        return
$value;
    }
   
public function shift() {
       
$value = array_shift($this->liste);
       
$this->nb_elements = count($this->liste);
        return
true;
    }
}
?>
really quick function
26-Jan-2008 05:37
function array_flatten($a){ //flattens multi-dim arrays (distroys keys)
    $ab = array(); if(!is_array($a)) return $ab;
    foreach($a as $value){
        if(is_array($value)){
            $ab = array_merge($ab,array_flatten($value));
        }else{
            array_push($ab,$value);
        }
    }
    return $ab;
}
Jck_true (leave out the &#39;_&#39; at gmail dot com)
25-Jan-2008 07:00
A usefull function that returns a flat array.
I use it in a template system. Let the user pass a multidimensional array. Convert it using my function. Then use
<?php
$array
= flatten($array,'','{$','}','->');
echo
str_replace(array_keys($array),array_values($array),$template)
/**
* Flattens out an multidimension array
* Using the last parameters you can define the new key based on the old path.
* @param array $array A multidimension array
* @param string $prefix Internal perfix parameter - leave empty.
* @param string $start_string What string should start the final array key?
* @param string $end_string What string should end the final array key?
* @param string $seperator The string that should seperate the piecies in final array key path
* @return array Returns the flat array
*/
function flatten($array, $start_string= '{$',$end_string= '}',$seperator='->',$prefix="") {
 
$return = array();
  foreach(
$array as $key=>$value) {
    if (
is_array($value)) {
     
$return = array_merge($return, Parser_method_replace::flatten($value, $prefix.$key.$seperator,$start_string,$end_string,$seperator));
    } else
     
$return [$start_string.$prefix.$key.$end_string] = $value;
  }
  return
$return;
}
}
?>
Example:
$template = 'My string with replacement {$test->subkey}';
{$test->subkey} will get replaced with $array['test']['subkey']
chaos dot global dot net at gmail dot com
03-Jan-2008 08:53
if some one will need to convert array to php code use this function:

DEFINE('OFFSET_DELIMETER', "\t");

function array2php($array, $offset = OFFSET_DELIMETER)  {
    $text = '';
    foreach($array as $k => $v) {
        if (is_array($v)) {
            $text .= "{$offset}'{$k}' => array(\n".array2php($v, $offset.OFFSET_DELIMETER)."$offset)";
        } else {
            $text .= "{$offset}'{$k}' => ".(is_string($v)? "'$v'": $v);
        }
        $text .= ",\n";
    }
    if ($len = strlen($text)) $text[$len - 2] = " ";
    return $text;
}
Hayley Watson
17-Oct-2007 08:10
Regarding cyberchrist at futura dot net's function. It makes an unnecessary array_merge(); the elements of $b that are merged with those of $a are immediately removed again by the array_diff(). The "limiting to known values" is entirely unnecessary, in other words: arrays already only contain "known values".

Also, the description and function only address the issue of whether $a is a subset of $b, not whether it is a proper subset. For $a to be a proper subset of $b, it must also be the case that $b is not a subset of $a.

Taking those points into account (and a personal aesthetic dislike of "if(test) return true; else return false;" gives:

<?php
function is_subset($a, $b)
{
    return
count(array_diff($a,$b))==0;
}

function
is_proper_subset($a, $b)
{
    return
is_subset($a, $b) && !is_subset($b, $a);
}
?>
cyberchrist at futura dot net
15-Oct-2007 10:33
Lately, dealing with databases, I've been finding myself needing to know if one array, $a, is a proper subset of $b.

Mathematically, this is asking (in set theory) [excuse the use of u and n instead of proper Unicode):
 
( A u B ) n ( ~ B )

What this does is it first limits to known values, then looks for anything outside of B but in the union of A and B (which would be those things in A which are not also in B).

If any value exists in this set, then A is NOT a proper subset of B, because a value exists in A but not in B.  For A to be a proper subset, all values in A must be in B.

I'm sure this could easily be done any number of ways but this seems to work for me.  It's not got a lot of error detection such as sterilizing inputs or checking input types.

// bool array_subset( array, array )
// Returns true if $a is a proper subset of $b, returns false otherwise.

function array_subset( $a, $b )
{
    if( count( array_diff( array_merge($a,$b), $b)) == 0 )
        return true;
    else
        return false;
}
Kazuyoshi Tlacaelel
30-Aug-2007 03:56
<?php
/**
 * converts a multidimensional array to a flat array
 *
 * trying to keep the original names of the keys
 * if repeated keys are found a hash will be added to the
 * keys trying to keep as much as possible of the original
 * key context
 *
 * september 30 2007
 *
 * PHP version 5
 *
 * @license         GPL
 *
 */

$array = array ( 0 => array ( 0 => 1, 1 => 2, 2 => array ( 0 => 3, 1 => 4, 2 =>
array (
0 => 5, 1 => 6, 2 => array ( 0 => 7, 1 => 8,),),), 3 => array (
   
0 => array ( 0 => 9, 1 => 10, 2 => array ( 0 => 11, 1 => 12,
   
2 => array ( 0 => 13, 1 => 14, 2 => array ( 0 => 15, 1 => 16,),),),),
   
1 => array ( 0 => 17, 1 => 18,),),), 1 => array ( 0 => 19, 1 => 20,),
   
2 => array ( 0 => array ( 0 => 21, 1 => 22, 2 => array ( 0 => 23, 1 => 24,
   
2 => array ( 0 => 25, 1 => 26, 2 => array ( 0 => 27, 1 => 28,),),),),
   
1 => array ( 0 => 29, 1 => 30,),),);

/**
 * transforms a multidimensional array to a flat array
 *
 * the parameter is referenced
 * so no returning value is needed
 * @param array $array the multidimensional array to flat
 * @return void
 */
function array_flatten(&$array)
{
    function
has_arrays($array)
    {
        foreach (
$array as $item) {
            if (
is_array($item)) {
                return
true;
            }
        }
        return
false;
    }

    function
copy_array(&$array, $array_key)
    {
       
$array2 = $array[$array_key];
        unset(
$array[$array_key]);
        foreach (
$array2 as $subkey => $subvalue) {
            if (
array_key_exists($subkey, $array)) {
               
$array[generate_unique_key($subkey)] = $subvalue;
            } else {
               
$array[$subkey] = $subvalue;
            }
        }
    }

    function
generate_unique_key($key)
    {
        if (
strlen($key)>8) {
           
$key = $key[0] . $key[1] . $key[2];
        }
       
$id = $key . '_';
       
$uid = uniqid();
       
$len = strlen($uid);
       
$max = (9 - strlen($key));
        for (
$c = $len; ; $c --) {
           
$id .= $uid[$c];
            if (
$c == ($len - $max)) {
                break;
            }
        }
        return
$id;
    }

    function
get_array_indexes($array)
    {
       
$ret_array = array();
        foreach (
$array as $key => $value) {
            if (
is_array($value)) {
               
$ret_array[] = $key;
            }
        }
        return
$ret_array;
    }

    while(
has_arrays($array)) {
        foreach (
get_array_indexes($array) as $key) {
           
copy_array($array, $key);
        }
    }
}

   
array_flatten($array);
   
array_multisort($array);
   
var_export($array);

   
/**
     *  OUTPUT
     *
     *  array (
     *    0 => 1,
     *    '1_403767b6' => 2,
     *    '0_793767b6' => 3,
     *    '1_8a3767b6' => 4,
     *    '0_454767b6' => 5,
     *    '1_564767b6' => 6,
     *    '0_035767b6' => 7,
     *    '1_345767b6' => 8,
     *    '0_e74767b6' => 9,
     *    '1_f84767b6' => 10,
     *    '0_855767b6' => 11,
     *    '1_a65767b6' => 12,
     *    '0_4e5767b6' => 13,
     *    '1_6f5767b6' => 14,
     *    '0_566767b6' => 15,
     *    '1_876767b6' => 16,
     *    '0_5b4767b6' => 17,
     *    '1_6c4767b6' => 18,
     *    '0_d43767b6' => 19,
     *    1 => 20,
     *    '0_4e3767b6' => 21,
     *    '1_5f3767b6' => 22,
     *    '0_ad4767b6' => 23,
     *    '1_ce4767b6' => 24,
     *    '0_485767b6' => 25,
     *    '1_695767b6' => 26,
     *    '0_116767b6' => 27,
     *    '1_426767b6' => 28,
     *    '0_814767b6' => 29,
     *    '1_924767b6' => 30,
     *  )
     */
?>
mo dot longman at gmail dot com
31-Jul-2007 03:27
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.

to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);

You can also stringify objects, numbers, etc.
g4wx3
19-Jul-2007 06:16
I needed a function to convert a php array into a javascript array.
No problem i found it on "the net".

But the function i found wasn't good enough, instead of return a string with javascript-array it echoed directly everything.
I wanted to write the string to a file, when calling the function out of my function libary.

Secondly, there where minor "bugs" in the script, when you're original array contained characters like line breaks(\r\n,..), or quotes('), it would hack up the javascript array

Sow, i changed the function and fixed the bug.

<?php
//SUPER COOL : http://www.communitymx.com/content/article.cfm?page=3&cid=7CD16
//Checkout:  REVERSE: http://www.hscripts.com/tutorials/php/jsArrayToPHP.php
//Convert a PHP array to a JavaScript one (rev. 4)
//Changlog by g4wx3: echo replaced by $output, added function output
function output($string) //make javascript ready
   
{
   
$string = str_replace( array( '\\' , '\'' ), array('\\\\', '\\\'') , $string); //-> for javascript array
   
$string = str_replace(  array("\r\n", "\r", "\n") , '<br>' , $string);    //nl2br
   
return $string;
    }
function
arrayToJS4($array, $baseName ) {
   
//Write out the initial array definition
//v4    echo ($baseName . " = new Array(); \r\n ");
   
$output = $baseName . " = new Array(); \r\n ";

   
//Reset the array loop pointer
   
reset ($array);

   
//Use list() and each() to loop over each key/value
    //pair of the array
   
while (list($key, $value) = each($array)) {
        if (
is_numeric($key)) {
       
//A numeric key, so output as usual
       
$outKey = "[" . $key . "]";
        } else {
       
//A string key, so output as a string
       
$outKey = "['" . $key . "']";
        }
     
        if (
is_array($value)) {
       
//The value is another array, so simply call
        //another instance of this function to handle it
       
$output .= arrayToJS4($value, $baseName . $outKey);
        } else {

           
//Output the key declaration
//v4            echo ($baseName . $outKey . " = ");     
           
$output .= $baseName . $outKey . " = ";
           
           
//Now output the value
           
if (is_string($value)) {
               
//Output as a string, as we did before      
//v4                echo ("'" . output($value) . "'; \r\n ");
               
$output .= "'" . output($value) . "'; \r\n ";
            } else if (
$value === false) {
               
//Explicitly output false
//v4                echo ("false; \r\n");
               
$output .= "false; \r\n";
            } else if (
$value === NULL) {
               
//Explicitly output null
//v4                echo ("null; \r\n");
               
$output .= "null; \r\n";
            } else if (
$value === true) {
               
//Explicitly output true
//v4                echo ("true; \r\n");
               
$output .= "true; \r\n";
            } else {
           
//Output the value directly otherwise
//v4            echo ($value . "; \r\n");
           
$output .= $value . "; \r\n";
            }
        }
    }
return
$output;
}
?>
You can use this for printing $_GET array, for example
peanutpad at msn dot com
16-Jun-2007 07:15
heres a function from http://www.linksback.org  Feedback welcome, of course!  Public domain, yadda yadda.

function mySort(&$array,$key) {
    if (!is_array($array) || count($array) == 0) return true;
    $assocSortCompare  = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';

    if (is_numeric($array[0][$key])) {
      $assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
    } else {
      $assocSortCompare.= ' return strcmp($a,$b);';
    }

    $assocSortCompare = create_function('$a,$b',$assocSortCompare);
    return usort($array,$assocSortCompare);
}
webdev at svbeatrix dot com
12-Jun-2007 01:06
Bugs happen, but how can people post functions that WON'T EVEN COMPILE!  I truly detest finding a cool code snippet or function and then having to debug them. Sorry for the rant, but I have experienced this scenario a number of times.  TEST YOUR CODE, THEN POST!

Here is a revised and corrected previously posted function ArrayDepth, which had 3 bugs and yes, would not compile.

function ArrayDepth($Array,$DepthCount=-1) {
// Find maximum depth of an array
// Usage: int ArrayDepth( array $array )
// returns integer with max depth
// if Array is a string or an empty array it will return 0
  $DepthArray=array(0);
  $DepthCount++;
  $Depth = 0;
  if (is_array($Array))
    foreach ($Array as $Key => $Value) {
      $DepthArray[]=ArrayDepth($Value,$DepthCount);
    }
  else
    return $DepthCount;
  return max($DepthCount,max($DepthArray));
}
sid dot pasquale at gmail dot com
30-May-2007 06:57
<?php
/* This function allow you to transform a multidimensional array
   in a simple monodimensional array.
   Usage: array_walk($oldarray, 'flatten_array', &$newarray);
   For example, this code below shows to you:
        Array
        (
            [1] => Array
                (
                    [0] => 1
                    [1] => 2
                )
       
            [2] => Array
                (
                    [0] => 3
                    [1] => 4
                )
       
        )
       
        Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
        )
*/

function flatten_array($value, $key, &$array) {
    if (!
is_array($value))
       
array_push($array,$value);
    else
       
array_walk($value, 'flatten_array', &$array);
 
}
 
$oldarray = array(
   
1 => array(1,2),
   
2 => array(3,4)
);
$newarray = array();
array_walk($oldarray, 'flatten_array', &$newarray);
echo
"<pre>";
print_r($oldarray);
print_r($newarray);
echo
"</pre>";
?>
info at dyflexis dot nl
18-Apr-2007 05:13
A modernized version of the flatten_array() functies written by

davidj at boundlessgallery dot DISLIKESPAM dot com
on 02-Apr-2004 03:10

This function is able to work with associative arrays