mohsen ny
mohsen ny

Reputation: 127

getting values from associative arrays in php

I'm programming in php for years, but i have encountered a redicilous problem and have no idea why it has happened. I guess i'm missing something, but my brain has stopped working! I have an ass. array and when i var_dump() it, it's like this:

 array
  0 => 
    array
      4 => string '12' (length=2)
  1 => 
    array
      2 => string '10' (length=2)
  2 => 
    array
      1 => string '9' (length=1)

I want to do something with those values like storing them in an array, (12, 10, 9), but I dont know how to retrieve it! I have tested foreach(), array_value(), but no result. No matter what i do, the var_dump() result is still the same! by the way i'm using codeigniter framework, but logically it should have nothing to do with the framework thanks guys

Upvotes: 0

Views: 2091

Answers (5)

Baba
Baba

Reputation: 95161

You can try using array_map

$array = array(
        0 => array(4 => '12'),
        1 => array(2 => '10'),
        2 => array(1 => '9'));

$array = array_map("array_shift", $array);
var_dump($array);

Output

array
  0 => string '12' (length=2)
  1 => string '10' (length=2)
  2 => string '9' (length=1)

Upvotes: 1

Sam Dufel
Sam Dufel

Reputation: 17608

If you have an unknown depth, you can do something like this:

$output = array();
array_walk_recursive($input, function($value, $index, &$output) {
    $output[] = $value;
}, $output);

Upvotes: 0

shortstuffsushi
shortstuffsushi

Reputation: 2330

If you want them to end up in an array, declare one, then iterate over your items.

$arr = new array();

foreach ($arrItem in $yourArray) {
  foreach ($innerArrItem in $arrItem) {
    array_push($arr, $innerArrItem);
  }
}

print_r($arr);

Upvotes: 0

poudigne
poudigne

Reputation: 1766

like this:

for ($i = count($array) ; $i >= 0 ; $i--) {
    foreach($array[$1] as $k => $v) {
        echo $k . "=>".$v;
    }
}

Upvotes: 0

JvdBerg
JvdBerg

Reputation: 21866

You can access them like this:

$array[0][4]= '13'; 
$array[1][2]= '11'; 
$array[2][1]= '10'; 

var_dump($array); gives this result:

    array(3) { 
      [0]=> array(1) { 
         [4]=> string(2) "13" } 
      [1]=> array(1) { 
         [2]=> string(2) "11" } 
      [2]=> array(1) { 
         [1]=> string(2) "10" } 
    }

Upvotes: 0

Related Questions