仅使用数组索引号从关联数组中访问值

时间:2016-02-26 02:20:41

标签: php arrays multidimensional-array associative-array

首先我有这个关联数组

$players = array("group1" => array("player1" => "Kevin Durant", "player2" => "Kyrie Irving"), "group2" => array("player1" => "Demian Lillard", "player2" => "Derrick Rose"));

我知道我可以使用这种循环方式

//create an empty array to be used as a container for our looped array
$data_arrays = array();
foreach($players as $data=>$key):
    array_push($data_arrays,$key['player1'],$key['player2']);
endforeach;

但我想要的是在那里获得数据索引的价值基础,例如

foreach($players as $data=>$key):
    array_push($data_arrays,$key[0],$key[1]);
endforeach;

但不幸的是,遗憾的是,它让我感到错误,

  

未定义的偏移量:0

请提供任何帮助,线索,建议,建议和想法吗?

2 个答案:

答案 0 :(得分:2)

您可以使用array_values()

foreach($players as $data=>$key):
    $groupPlayers = array_values( $key );
    array_push($data_arrays,$groupPlayers[0],$groupPlayers[1]);
endforeach;

作为旁注:您对变量名$data$key的使用相当不正统:关键是数组元素的索引,数据通常被认为是数组元素的值。所以我建议改掉它们,即:

foreach($players as $key=>$data):
    $groupPlayers = array_values( $data );
    array_push($data_arrays,$groupPlayers[0],$groupPlayers[1]);
endforeach;

答案 1 :(得分:2)

这样的事情会起作用:

<?php
$players = array("group1" => array("player1" => "Kevin Durant", "player2" => "Kyrie Irving"), "group2" => array("player1" => "Demian Lillard", "player2" => "Derrick Rose"));

$data_arrays = array();
foreach($players as $data => $key):
    $data_arrays = array_merge($data_arrays, array_values($key));
endforeach;

print_r($data_arrays);

演示:http://sandbox.onlinephpfunctions.com/code/e5133c3f317beccc5c2b0bbd56770359a1040c37

使用array_reduce的另一种更短的方法:

$players = array("group1" => array("player1" => "Kevin Durant", "player2" => "Kyrie Irving"), "group2" => array("player1" => "Demian Lillard", "player2" => "Derrick Rose"));

$players = array_reduce($players, function(&$players, $v) {return array_merge(array_values($players), array_values($v));}, array());

print_r($players);

演示:http://sandbox.onlinephpfunctions.com/code/92c51ac92fdfde40df3e4fc9d469d52d19f05376