如何将数组中的值提取到变量中?

时间:2014-10-30 06:31:59

标签: php

我正在使用以下代码打印我的数组:

//SQL Query
$query = "SELECT wp_arf_entry_values.entry_value, wp_arf_entry_values.id FROM wp_arf_entry_values WHERE entry_id=1";

//Execute the SQL query and return records
$result = mysql_query($query);

while($row = mysql_fetch_assoc($result)){
     $results[] = $row;
}

//Print array in human readable form
print("<pre>".print_r($results,true)."</pre>");

这是输出:

Array
(
    [0] => Array
        (
            [entry_value] => John
            [id] => 1
        )

    [1] => Array
        (
            [entry_value] => Doe
            [id] => 2
        )

    [2] => Array
        (
            [entry_value] => 19
            [id] => 3
        )

    [3] => Array
        (
            [entry_value] => Male
            [id] => 4
        )
)

我很难弄清楚如何将数组的值提取到变量中,就像这样(不是实际的代码,只是一个例子):

$fName = 'entry_value' that has ID = 1
$lName = 'entry_value' that has ID = 2
$age = 'entry_value' that has ID = 3
$genre = 'entry_value' that has ID = 4

我在这里研究了过去一小时,但我找不到能帮助我的答案。有什么可行的方法呢?

4 个答案:

答案 0 :(得分:3)

假设:id值在数据库中是唯一的

将您的代码更改为

$results = array();
while($row = mysql_fetch_assoc($result)){
     $results[$row['id']] = $row['entry_value'];
}

//Print array in human readable form
print("<pre>".print_r($results,true)."</pre>");

你可以将你的价值观作为:

$fName = $results['1']
$lName = $results['2']
$age   = $results['3']
$genre = $results['4']

答案 1 :(得分:1)

<?php
// set dummy data
$data = [
    ['entry_value' => 'John', 'id' => 1],
    ['entry_value' => 'Doe', 'id' => 2],
    ['entry_value' => '19', 'id' => 3],
    ['entry_value' => 'Male', 'id' => 4],
];

$data = array_column($data, 'entry_value', 'id');
$fName = $data[1];
$lName = $data[2];
$age = $data[3];
$genre = $data[4];

答案 2 :(得分:0)

这不是最优雅的解决方案,但有效:

 foreach($results as $result){
    switch ($result['id']){
        case 1:
            $fname = $result['entry_value'];
            break;

        case 2:
            $lName  = $result['entry_value'];
            break;

        case 3:
            $age  = $result['entry_value'];
            break;
        case 4:
            $genre  = $result['entry_value'];
            break;
    }
    echo "fname = $fname | lName = $lName | age = $age | genre = $genre\n" ;
}

这样,结果顺序无关紧要......因此,$ results数组的顺序不正确,无论如何都会有效。

答案 3 :(得分:0)

你必须通过循环,代码在下面给出

$fName = $lName = $age = $genre = "";
foreach($results AS $result){
switch($result['id']){
case 1:
$fName = $result['entry_value'];
break;
case 2:
$lName = $result['entry_value'];
break;
case 3:
$age = $result['entry_value'];
break;
case 4:
$genre = $result['entry_value'];
break;
}
}
echo $fName." ".$lName." is ".$genre." and ".$age."years old.";