Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

array_combine

(PHP 5)

array_combine --  Создать новый массив, используя один массив в качестве ключей, а другой в качестве соответствующих значений

Описание

array array_combine ( array keys, array values )

Возвращает array, используя значения массива keys в качестве ключей и значения масссива values в качестве соответствующих значений.

Возвращает FALSE, если количество элементов в исходных массивах не совпадает или если массивы пусты.

Пример 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_merge(), array_walk(), и array_values().



array_count_values> <array_chunk
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
array_combine
Khaly
04-Oct-2007 02:11
This is the fonction for PHP4 :

function array_combine($arr1,$arr2) {
   $out = array();
   foreach($arr1 as $key1 => $value1)    {
    $out[$value1] = $arr2[$key1];
   }
   return $out
}
Hayley Watson
20-Aug-2007 10:17
Fred's code just previous isn't the simplest, given...
<?php
function array_combine($keys, $values)
{
   
$result = array();
    foreach(
array_map(null, $keys, $values) as $pair)
       
$result[$pair[0]]=$pair[1];
    return
$result;
}
?>
...if you're equally happy to avoid any sort of error checking of course.
Fred
09-Aug-2007 03:49
I read many workaround functions for users with php < 5
Here is mine (the simpliest I think) :

<?php
function array_combine($keys, $values) {
   
$result = array() ;
    while( (
$k=each($keys)) && ($v=each($values)) ) $result[$k[1]] = $v[1] ;
    return
$result ;
}
?>
royanee at yahoo dot com
06-Aug-2007 10:11
This correctly accounts for the error conditions, and actually works. The previous note appears to set all the values in the result array to the value of the last item in the values input array.
<?php
function array_combine( $keys, $values )
{
   if( !
is_array($keys) || !is_array($values) || empty($keys) || empty($values) || count($keys) != count($values) )
   {
     
trigger_error( "array_combine() expects parameters 1 and 2 to be non-empty arrays with an equal number of elements", E_USER_WARNING );
      return
false;
   }
  
$keys = array_values($keys);
  
$values = array_values($values);
  
$result = array();
   foreach(
$keys as $index => $key )
   {
     
$result[$key] = $values[$index];
   }
   return
$result;
}
?>
robertark at gmail dot com
02-Aug-2007 04:43
All of those 'array_combine' emulators did -not- work for me, so I created one of my own, out randomly, and it worked for me, maybe you can give it a shot and let me know how it works. Thanks..

function array_combine($arr1, $arr2)
{
  $buffer = array();
  foreach($arr1 as $key1 => $arr_1)
  {
    foreach($arr2 as $key2 => $arr_2)
      $buffer[$arr_1] = $arr_2;
  }
  return $buffer;
}
muppis
21-Jun-2007 05:46
I found these workarounds for PHP 4.4.x non-working with $_POST and $_GET arrays except Ivo van Sandick's one. Works well, even my client ISP denies to update to 4.4.7 at least..
toth dot janas at gmail dot com
01-Jun-2007 02:21
Under this note i send yesterday a function that in array show once the dupicated elements. Sorry, the function is wrong. I corrected the error and i write a new function is working right.
/tested/.

The test array is:

$test = array(
    0 => 1,
    1 => 2,
    2 => 1,
    3 => 3,
    4 => 4,
    5 => 2,
    6 => 5,
    7 => 4
);

the function:

function array_no_duplicate($array_tmb){
    $temp = array();
     foreach ($array_tmb as $value){
     $if_one = 0;
         foreach ($temp as $new_value) {
            if($new_value == $value)  $if_one = 1;
          }
     if($if_one == 0)  array_push($temp, $value);    
    }
    return $temp;
}

example:
var_dump(array_no_duplicate($test));

this output will show array without duplicated elements.

Good work!
toth dot janas at gmail dot com
31-May-2007 12:48
If you have an array and include duplicated element, and you want to that this element just show once in array, then this function is very good solution.

function array_no_duplicate($array_tmb){
    $new_array = array();
    for($i = 0; $i < count($array_tmb); $i++){
    $van = 0;
        for($j = 0; $j < count($array_tmb); $j++){
         if( $new_array[$j] == $array_tmb[$j]) $van = 1;
        }   
    if($van == 0){
         $new_array[$i] = $array_tmb[$i];
    }else continue;        
    }
    return $new_array;
}
Q1712 at online dot ms
22-Apr-2007 06:04
there was one exaple missing in my priviouse post:
<?php
print_r
( array(array()), array("array()") );
?>
prints:
Array
(
    [Array] = array()
)

@admin: please merge these 2 posts
Q1712 at online dot ms
22-Apr-2007 05:56
If a value is existing twice in the $keys-array the last one overwrites the others, wich makes the returned array shorter than the given once, as usual.
If a value of the values-array is double/float, bool or array the string representaion is used, not the integer representation as usual.

<?php
print_r
(
 
combine(
    array(
'a', 'a', 'a', 0, false, 1, true, 2, 7/3),
    array(
"first 'a'", "second 'a'", "third 'a'", "0", "false", "1", "true", "2", "7/3")
  )
);

print_r(
  array (
'a' => "first 'a'", 'a' => "second 'a'", 'a' => "third 'a'", 0 => "0", false => "false", 1 => "1", true => "true", 2 => "2", 7/3 => "7/3")
);
?>

prints:
Array
(
    [a] => third 'a'
    [0] => 0
    [] => false
    [1] => true
    [2] => 2
    [2.33333333333] => 7/3
)
Array
(
    [a] => third 'a'
    [0] => false
    [1] => true
    [2] => 7/3
)
chriswillarddesign at yahoo dot com
10-Apr-2007 08:26
Here is my take on the combine function for PHP < 5:

<?
// Combines two associate arrays by making a array with the key being $a1 and the value $a2.
    function array_combine($a1,$a2)
    {
        for($i=0;$i<count($a1);$i++)
            $ra[$a1[$i]] = $a2[$i];
        if(isset($ra)) return $ra; else return false;
    }

?>
Wiebe
26-Mar-2007 02:05
When you have not the use off PHP 5.

The workaround off  'Ivo van Sandick' can be much shorter.
I use my function:

<?
// combine $arr with $arr_to_key where $arr_to_key becomes key of $arr.

 function array_comb($arr, $arr_to_key){

          $i = 0;
          foreach($arr_to_key AS $value){
                  $arr_combined[$value] = $arr[$i];
                  $i++;
          }

          RETURN $arr_combined;
 }

 //example.
 $arr_1[0] = 'apple';
 $arr_1[1] = 'banana';
 $arr_2[0] = 'green';
 $arr_2[1] = 'yellow';

 $arr_comb = array_comb($arr_1, $arr_2);

 //$arr_comb['green'] = 'apple'
 //$arr_comb['yellow'] = 'banana'

?>
neoyahuu at yahoo dot com
19-Mar-2007 09: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
)
Ivo van Sandick
02-Sep-2005 01:04
Such a useful function, and only since version 5! Why an emulation for earlier PHP versions has not been posted long ago, is a mystery:

<?php
function array_combine_emulated( $keys, $vals ) {
 
$keys = array_values( (array) $keys );
 
$vals = array_values( (array) $vals );
 
$n = max( count( $keys ), count( $vals ) );
 
$r = array();
 for(
$i=0; $i<$n; $i++ ) {
 
$r[ $keys[ $i ] ] = $vals[ $i ];
 }
 return
$r;
}
?>
ifeghali at interveritas dot net
26-Feb-2005 10: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
20-May-2004 07: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: Sat, 27 Jan 2007
 
 
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571