1

Supposedly I have an array like this:

$shop = array( array("name"=>"Tom", "level"=> 1.25 ),
               array("name"=>"Mike","level"=> 0.75 ),
               array("name"=>"John","level"=> 1.15 ) 
             ); 

How do I make an array with all name values and the keys being the position of theri original array. I know I could iterate through, and put in another array, but are there any functions?

Sorry if I was confusing. My desired output would be:

array(0=>"Tom",1=>"Mike",2=>"John");

So basicaly what select does in sql.

4

4 回答 4

5

从 PHP 5.3.0 开始,你可以使用这个:

$result = array_map(
    function($x) {
        return $x['name'];
    }, $shop);

print_r($result);

在 5.3.0 之前,您可以使用create_function进行回调。

于 2013-04-05T10:06:37.610 回答
2

从 php 5.5 开始,您可以使用

$names = array_column($shop, 'name');
于 2019-07-30T11:21:51.920 回答
0
$shop = array( array("name"=>"Tom", "level"=> 1.25 ),
               array("name"=>"Mike","level"=> 0.75 ),
               array("name"=>"John","level"=> 1.15 ) 
             );
$newArr = array();

foreach($shop as $key=>$val){
$newArr[$key] = $val['name'];
}
print_r($newArr);
于 2013-04-05T10:06:13.587 回答
-2

你可以用foreach

<?php

$shop = array( array("name"=>"Tom", "level"=> 1.25 ),
               array("name"=>"Mike","level"=> 0.75 ),
               array("name"=>"John","level"=> 1.15 ) 
             ); 

$newar = array();
foreach($shop as $subarr){
    $newar[] = $subarr['name'];
}

print_r($newar);

?>
于 2013-04-05T10:04:12.870 回答