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

search for in the

array_count_values> <array_chunk
Last updated: Fri, 24 Jul 2009

view this page in

array_combine

(PHP 5)

array_combine키를 위한 배열과 값을 위한 배열을 사용하여 배열을 생성

설명

array array_combine ( array $keys , array $values )

keys 배열에서의 값들을 키로 사용하고 values 배열에서의 값들을 해당 값들로 사용하여 array를 생성합니다.

인수

keys

키로 사용할 배열. 키로 적합하지 않은 값은 string으로 변환됩니다.

values

값으로 사용할 배열

반환값

결합된 array를 반환합니다. 각 배열의 원소 수가 일치하지 않거나 배열이 비어 있으면 FALSE를 반환합니다.

오류/예외

keysvalues 가 비어있거나 원소 수가 일치하지 않으면 E_WARNING이 발생합니다.

예제

Example #1 간단한 array_combine() 예제

<?php
$a 
= array('green''red''yellow');
$b = array('avocado''apple''banana');
$c array_combine($a$b);

print_r($c);
?>

위 예제의 출력:

Array
(
    [green]  => avocado
    [red]    => apple
    [yellow] => banana
)

참고



array_count_values> <array_chunk
Last updated: Fri, 24 Jul 2009
 
add a note add a note User Contributed Notes
array_combine
xavier at api-meal dot eu
23-Sep-2009 10:37
<?php
/**
 * Return alternatives defined by values of each parameters.
 *
 * Exemple :
 *
 * array_alternatives(array('foo','bar'), array('baz', 'qux'));
 * array(
 *     array('foo', 'baz'),
 *     array('bar', 'baz'),
 *     array('foo', 'qux'),
 *     array('bar', 'qux'),
 * );
 *
 * array_alternatives(array('a'), array('simple-minded'), array('solution'));
 * array(
 *     array('a', 'simple-minded', 'solution')
 * );
 *
 * array_alternatives(array('a'), array('red', 'blue'), array('car'));
 * array(
 *     array('a', 'red',  'car'),
 *     array('a', 'blue', 'car'),
 * );
 * 
 * @param array $first_element
 * @param array $second_element
 * @return array
 * @author Xavier Barbosa
 */
function array_alternatives(array $first_element, array $second_element)
{
   
$lists = func_get_args();
   
$total_lists = func_num_args();
   
    for(
$i=0; $i<$total_lists; $i++)
    {
       
$list =& $lists[$i];
        if (
is_array($list) === FALSE)
            throw new
Exception("Parameter $i is not an array.");
        if (
count($list) === 0)
            throw new
Exception("Parameter $i has no element.");
        unset(
$list);
    }
   
   
// Initialize our alternatives
   
$alternatives = array();
    foreach(
$lists[0] as &$value)
    {
       
array_push($alternatives, array($value));
        unset(
$value);
    }
    unset(
$lists[0]);
   
   
// Process alternatives
   
for($i=1; $i<$total_lists; $i++)
    {
       
$list =& $lists[$i];
       
       
$new_alternatives = array();
        foreach(
$list as &$value)
        {
            foreach(
$alternatives as $_)
            {
               
array_push($_, $value);
               
array_push($new_alternatives, $_);
            }
        }
       
       
// Rotate references, it's cheaper than copy array like `$alternatives = $new_alternatives;`
       
$alternatives =& $new_alternatives;
        unset(
$new_alternatives, $list, $lists[$i]);
    }
   
    return
$alternatives;
}
?>
quecoder at gmail
26-Aug-2008 07:00
<?php
// If they are not of same size, here is solution:

$abbreviations = array("AL", "AK", "AZ", "AR", "TX", "CA");
$states = array("Alabama", "Alaska", "Arizona", "Arkansas");
function
combine_arr($a, $b)
{
   
$acount = count($a);
   
$bcount = count($b);
   
$size = ($acount > $bcount) ? $bcount : $acount;
   
$a = array_slice($a, 0, $size);
   
$b = array_slice($b, 0, $size);
    return
array_combine($a, $b);
}
$combined = combine_arr($abbreviations, $states);
print_r($combined);

//  Output
//  Array ( [AL] => Alabama [AK] => Alaska [AZ] => Arizona
//  [AR] => Arkansas )
?>
J.D.D.
09-Aug-2008 08:31
This may be obvious, but I don't see anything about it on the manual page, so a friendly warning...  The array you are using as keys must have all unique values.  If not, array elements get dropped. 

<?php
$arr_notUnique
= array('one' , 'one' , 'two');
$arr_b = array('red' , 'green' , 'blue');

$arr_combo = array_combine($arr_notUnique, $arr_b);
?>

Results:  Array ( [one] => green [two] => blue )

NOT:  Array ( [one] => red [one] => green [two] => blue )
Zoran
02-Apr-2008 12:57
Also, Khalys function only works if keys of both arrays are the same because array_combine ignores keys. An easy way to ignore them is by taking array_values(). Floats can be casted to strings to avoid overwriting.

So, the PHP4 function could look something like this:
<?php
function array_combine($arr1, $arr2) {
   
$out = array();
   
   
$arr1 = array_values($arr1);
   
$arr2 = array_values($arr2);
   
    foreach(
$arr1 as $key1 => $value1) {
       
$out[(string)$value1] = $arr2[$key1];
    }
   
    return
$out;
}
?>
Mike Jean
19-Mar-2008 05:59
Khaly's PHP4 code below does not work correctly in all cases. Consider when your array consists of floats:

<?php

$okay
= array(0, 10, 20, 30);
$not_okay = array(0, 0.5, 1, 1.5);

$foo = array_combine($okay, $okay);
$bar = array_combine($not_okay, $not_okay);

/*

Results:

$foo = {
  [0]=> int(0)
  [10]=> int(10)
  [20]=> int(20)
  [30]=> int(30)
}

$bar = {
  [0]=> float(0.5)
  [1]=> float(1.5)
}

*/

?>

What can you do? In my case, I was just zipping up some select-box options, so I converted everything in my floats to strings.
Khaly
04-Oct-2007 09:11
This is the function for PHP4 :

<?php

function array_combine($arr1,$arr2) {
  
$out = array();
   foreach(
$arr1 as $key1 => $value1)    {
   
$out[$value1] = $arr2[$key1];
   }
   return
$out
}

?>
neoyahuu at yahoo dot com
20-Mar-2007 04:36
Some tips for merging same values in an array

<?php
$array1
= array(1,2,3,4,5,6,7,8,9,10,11,12);
$array2 = array(1,2,3,13);

$merged = array_merge($array1,$array2);

// output normal array_merge
echo '<pre>After array_merge :
'
;
print_r($merged);
echo
'</pre>';

// do double flip for merging values in an array
$merged = array_flip($merged);
$merged = array_flip($merged);

// Output after
echo '<pre>After Double Flip :
'
;
print_r($merged);
echo
'</pre>';
?>

Output ::

After array_merge :
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 1
    [13] => 2
    [14] => 3
    [15] => 13
)

After Double Flip :
Array
(
    [12] => 1
    [13] => 2
    [14] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
    [9] => 10
    [10] => 11
    [11] => 12
    [15] => 13
)
ifeghali at interveritas dot net
26-Feb-2005 06:53
Use that code to group an array by its first element.

<?

function groupbyfirst($array)
{
    foreach (
$array as $row)
    {
       
$firstkey = array_keys($row);
       
$firstkey = $firstkey[0];
       
$key = $row[$firstkey];
        unset(
$row[$firstkey]);
       
$newarray[$key][] = $row;
    }
    return
$newarray;
}

?>

Example:

<?

$array
=
Array(
   
0 => Array('color' => 'red','name' => 'apple', 'quantity' => '3'),
   
1 => Array('color' => 'green','name' => 'pear', 'quantity' => '2'),
   
2 => Array('color' => 'yellow','name' => 'corn', 'quantity' => '3'),
   
3 => Array('color' => 'blue','name' => 'grape', 'quantity' => '4'),
   
4 => Array('color' => 'yellow','name' => 'banana', 'quantity' => '13'),
);

$output = groupbyfirst($array);
print_r($output);

?>

will return:

Array
(
 [red] => Array ( [0] => Array ( [name] => apple [quantity] => 3 ) )
 [green] => Array ( [0] => Array ( [name] => pear [quantity] => 2 ) )
 [yellow] => Array ( [0] => Array ( [name] => corn [quantity] => 3 ), [1] => Array ( [name] => banana [quantity] => 13 ) )
 [blue] => Array ( [0] => Array ( [name] => grape [quantity] => 4 ))
)

Or you can use mysql recordset:

<?
while ($row=mysql_fetch_array($result,MYSQL_ASSOC))
{
   
$firstkey = array_keys($row);
   
$firstkey = $firstkey[0];
   
$key = $row[$firstkey];
    unset(
$row[$firstkey]);
   
$newarray[$key][] = $row;
}
?>
aidan at php dot net
21-May-2004 02:15
This functionality is now implemented in the PEAR package PHP_Compat.

More information about using this function without upgrading your version of PHP can be found on the below link:

http://pear.php.net/package/PHP_Compat

array_count_values> <array_chunk
Last updated: Fri, 24 Jul 2009
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites