Vlad Eugen Nitu
Vlad Eugen Nitu

Reputation: 305

Get a string from an array inside an array

I have a function that returns an array from the database from which I have to display some data into the view.

If I do

print "<pre>";
print_r($names);
exit();

on the variable that stores the data it returns this:

Array
(
[0] => Array
        (
            [nume] => Eugen
        )
[1] => Array
        (
            [nume] => Roxanescu
        )
[2] => Array
        (
            [nume] => Georgiana
        )
[3] => Array
        (
            [nume] => Andrei
        )
)

I can't change the function I talk about in any way, I need to store each name in a different variable. At the end it should look like this:

name1 = "Eugen"
name2 = "Roxanescu"
name3 = "Georgiana"
name4 = "Andrei"

Thank you very much!

Upvotes: 1

Views: 52

Answers (4)

al&#39;ein
al&#39;ein

Reputation: 1727

I suggest you use an array and reference to each element of it as a variable, if it's really necessary.

$result = array();
foreach ($names as $n) {
    array_push($result, $n['nume']);
    echo "name".array_search($n['nume'], $result)." = ".$n['nume'];
}

Upvotes: 0

acupofjose
acupofjose

Reputation: 2159

Note entirely sure why you want to do this... But here's a function that should do what you're looking for.

This answer uses dynamic variable assignment, creating a new variable with a string ( $"name1", $"name2", etc ).

for($i = 0; $i < count($names); $i++) {
  $var_name = "name".$i;
  $$var_name = $names[$i]['nume'];
}

var_dump(get_defined_vars());

$name1, $name2, $name3 ... < count($names)

Upvotes: 1

bicho
bicho

Reputation: 134

You could assign a variable the data of your array;

<?php
    $name1=$names[0];
    $name2=$names[1];
    $name3=$names[2];
    $name4=$names[3];

    echo $name1." ".$name2." ".$name3." ".$name4;
?>

Upvotes: 1

Inceddy
Inceddy

Reputation: 760

$result = array();
array_walk($names, function ($value, $key) use (&$result) {
    $result[ 'name' . $key ] = $value['name'];
});
var_dump($result);

Upvotes: 0

Related Questions