php 如何在没有索引的情况下提取数组的键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15870659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:06:20  来源:igfitidea点击:

How to extract the keys and values of an array without index

phparraysextract

提问by Liuqing Hu

I want to extract data from an array (original array with key and value). After I extract the array, I want two new arrays, the first one with just the keys, the second one with just the values, and both without indexes (see code example).

我想从一个数组(带有键和值的原始数组)中提取数据。提取数组后,我想要两个新数组,第一个只有键,第二个只有值,并且都没有索引(参见代码示例)。

// original array 
$array = array(
    "name1"=>500
   ,"name2"=>400
   ,"name3"=>300
   ,"name4"=>200
   ,"name5"=>100
);

// after extraction
$array1 = array('name1','name2','name3','name4','name5');
$array2 = array(500,400,300,200,100);

// not like this
// $array1 = array(0=>'name1',1=>'name2',2=>'name3',3=>'name4',4=>'name5);
// $array2 = array(0=>500,1=>400,2=?300,3=>200,4=>100);

回答by Afriyandi Setiawan

$array1 = array_keys($array);
$array2 = array_values($array);

well, you can read here.

好吧,你可以在这里阅读。

In computer science, an array data structure or simply an array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored so that the position of each element can be computed from its index tuple by a mathematical formula.

在计算机科学中,数组数据结构或简单的数组是由一组元素(值或变量)组成的数据结构,每个元素由至少一个数组索引或键标识。存储一个数组,以便可以通过数学公式从其索引元组计算每个元素的位置。

回答by Francis Avila

$keys = array_keys($array);
$values = array_values($array);

Note however that array(0=>'item')and array('item')are exactly identicalas far as PHP is concerned. There is no such thing as a php array item without an index. If you do not supply an index PHP will silently add a numeric index.

但是,这种注意array(0=>'item')array('item')完全相同就PHP而言。没有没有索引的 php 数组项是不存在的。如果您不提供索引,PHP 将默默地添加一个数字索引。