Juliver Galleto
Juliver Galleto

Reputation: 9037

access values from a associative array only using there array index number

First I have this associative array

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

I know I can just use this way of looping

//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;

but what I want is get there value base on there array index, e.g.

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

but unfortunately and sadly, it returms me an error,

Undefined offset: 0

any help, clues, suggestions, recommendations, ideas please?

Upvotes: 1

Views: 33

Answers (2)

Decent Dabbler
Decent Dabbler

Reputation: 22783

You could use array_values():

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

As a side note: your use of the variable names $data and $key is rather unorthodox: the key is the index of an array element, data is usually considered the value of the array element. So I would suggest to switch them, i.e.:

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

Upvotes: 2

Aziz Saleh
Aziz Saleh

Reputation: 2707

Something like this would work:

<?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);

Demo: http://sandbox.onlinephpfunctions.com/code/e5133c3f317beccc5c2b0bbd56770359a1040c37

An Alternative, shorter way to do it using 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);

Demo: http://sandbox.onlinephpfunctions.com/code/92c51ac92fdfde40df3e4fc9d469d52d19f05376

Upvotes: 2

Related Questions