如何从数组 key=>value 中获得一个没有键的简单数组?

问题描述 投票:0回答:5

我有一个像这样的数组:

array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
并且只想获得我的价值观,例如这里:

简单标签=

array("35","37","43");

或者像这样,我应该得到一个列表更好:

simpleList=["35";"37";"43"]

我正在创建一个函数,因为我会多次需要它,所以这里是:

$simpleArray=array(); //don't know if this should be array, i'd like to have a list

foreach($valueAssoc as $key => $value{//array_push($simpleArray,$value);//NO it returns an array with keys 0 , 1 , etc
    //$simpleArray[]=$value; //same ! I don't want any keys

    //I want only an array without any index or key "tableau indexé sans clef"
    echo $value;
    //would like to have some method like this :
    $simpleArray.add($value);//to add value in my list -> can't find the php method
php arrays list key
5个回答
12
投票

如果你想要没有密钥,你应该使用

array_values()
json_encode()
(这意味着转换为字符串)像

这样的数组
$arr = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
print_r(json_encode(array_values($arr)));

输出:

["35","37","43"]

8
投票

无需为其创建函数,有一个内置函数

array_values()
,其功能与所需完全相同。

来自文档:

返回数组的所有值

示例:

$arr = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
print_r(array_values($arr)); // Array ( [0] => 35 [1] => 37 [2] => 43 )

8
投票

您正在寻找 array_values 它将仅返回键/值对中的值。

$arr = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$arrVals = array_values($arr);

其背后的代码与您期望的大致相同,其中有一个

foreach
循环并将结果推送到新数组。


3
投票

试试这个 -

$arrs = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
$array = (array_values($arrs)); 

echo "<pre>";
print_r($array);

0
投票

试试这个吧...

$Data_array = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

$output_array = array();

foreach($Data_array as $a) 
{
        array_push($output_array,$a->{$key_name});
}

// Output will be :
$output_array : ["35","37","43"]
© www.soinside.com 2019 - 2024. All rights reserved.