访问php变量中的一些值

时间:2021-09-24 02:14:59

I have an array variable $var. When I var_dump($var), it shows the following:

我有一个数组变量$ var。当我var_dump($ var)时,它显示以下内容:

array(2) {
   [0] => array(3) {
         ["name"] => string(7) "Ferrari" 
         ["speed"] => int(120)
         ["isActive"] => bool(true)
         }array(3) {
         ["name"] => string(7) "Porsche" 
         ["speed"] => int(100)
         ["isActive"] => bool(false)
         }
}

The question is: I want to access these values. For example, i want to save the speed value of Ferrari into a variable $speed.

问题是:我想访问这些值。例如,我想将法拉利的速度值保存为变量$ speed。

Something like check every element of array, If "name" = Ferrari, Set $speed= corresponding int value of choosen element of array.

比如检查数组的每个元素,如果“name”=法拉利,则设置$ speed =数组选择元素的对应int值。

What is the syntax of this in PHP.

PHP中的这个语法是什么?

Thanks in advance.

提前致谢。

3 个解决方案

#1


1  

$speed = null;
foreach ($var as $car) {
    if ($car['name'] == 'Ferrari') {
        $speed = $car['speed'];
    }
}
echo $speed;

Would be more reusable if you'll extend the array $var.

如果你扩展数组$ var,会更加可重用。

You can find basics of PHP here: W3Schools

你可以在这里找到PHP的基础知识:W3Schools

#2


0  

You just need to get the value from the array. Check isset to make sure the value exists if you want.

您只需要从数组中获取值。如果需要,请检查isset以确保该值存在。


$speed = (isset($var[0]['speed'])) ? $var[0]['speed'] : 0;

#3


0  

pls try this :

请试试这个:

$speed = 0;
if (isset($var[0]["name"]) && isset($var[0]["speed"]) && $var[0]["name"]=="Ferrari"){
    $speed = $var[0]["speed"];
}

#1


1  

$speed = null;
foreach ($var as $car) {
    if ($car['name'] == 'Ferrari') {
        $speed = $car['speed'];
    }
}
echo $speed;

Would be more reusable if you'll extend the array $var.

如果你扩展数组$ var,会更加可重用。

You can find basics of PHP here: W3Schools

你可以在这里找到PHP的基础知识:W3Schools

#2


0  

You just need to get the value from the array. Check isset to make sure the value exists if you want.

您只需要从数组中获取值。如果需要,请检查isset以确保该值存在。


$speed = (isset($var[0]['speed'])) ? $var[0]['speed'] : 0;

#3


0  

pls try this :

请试试这个:

$speed = 0;
if (isset($var[0]["name"]) && isset($var[0]["speed"]) && $var[0]["name"]=="Ferrari"){
    $speed = $var[0]["speed"];
}