简体   繁体   English

PHP:如何从类返回的数组中获取单个值?

[英]PHP: How to get single value from array that was returned from a class?

class Test {

    public function results() {

      $return['first'] = 'one';
      $return['second'] = 'two';

      return $return;

    }

}

$test = new Test;

print_r($test->results()); // Returns entire array

I just want to return a single specified element from the array, such as the value of key "second". 我只想从数组中返回一个指定的元素,例如键“ second”的值。 How do I do this without sifting through the entire array after it's returned? 返回数组后如何在不筛选整个数组的情况下执行此操作?

I just want to return a single specified element from the array, such as the value of key "second" 我只想从数组中返回一个指定的元素,例如键“ second”的值

Pass in an argument to identify which element to return, and return that (or false if it doesn't exist - for example); 传递参数以标识要返回的元素,然后返回(例如,如果不存在,则返回false);

public function results($key = null)
{
    $return['first'] = 'one';
    $return['second'] = 'two';

    // check the key exists
    if (!array_key_exists($key, $return)) {
        return false;
    }

    return $return[$key];
}

Then: 然后:

print_r($test->results('second')); // two

How do I do this without sifting through the entire array after it's returned? 返回数组后如何在不筛选整个数组的情况下执行此操作?

It's important to note that you do not need to "sift through the entire array" to retrieve a value by its key. 重要的是要注意,您不需要“遍历整个数组”即可通过键检索值。 You know the key, so you can access it directly. 您知道密钥,因此可以直接访问它。

class Test {

  private $arr; //private property of object

  __construct(){

    //create arr in constructor   
    $this->arr=[];//create new array

    $this->arr['first'] = 'one';
    $this->arr['second'] = 'two';

  }

  /**
  /* get array
  **/
  public function getResults(){

     return $this->arr;
  }

  /**
  /* get single array element
  **/
  public function getResult($key) {

     return isset($this->arr[$key])?$this->arr[$key]:null;//return element on $key or null if no result
  }

}

$test = new Test();

print_r($test->getResult("second")); // Returns array element
//or second possibility but the same result
print_r($test->getResults()["second"]); // Returns array element

Few advices: 一些建议:

Create data structure in constructor ($arr in this particular case) because creating it on very results method call is not any kind of using objects or objective programming. 在构造函数中创建数据结构(在这种情况下为$ arr),因为在非常结果方法调用上创建数据结构并不是使用对象或目标程序的任何形式。 Imagine that if array is created in results method then on every call new array is located in memory, this is not efficent, not optimal and gives no possibility to modify this array inside class Test. 想象一下,如果在results方法中创建了数组,那么每次调用时,新数组都位于内存中,这不是有效的,不是最优的,并且无法在Test类中修改此数组。

Next in method results add parameter to get only this key what is needed and hide all array in private class property $arr to encapsulate it in object. 方法结果中的下一个添加参数仅获得所需的键,并将所有数组隐藏在私有类属性$ arr中以将其封装在对象中。

And last my private opinion for naming style: 最后,我个人对命名风格的看法是:

Use camelCase when naming method names. 命名方法名称时,请使用camelCase

In PHP 5.4 and above: 在PHP 5.4及更高版本中:

print_r($test->results()['second']);

In older versions which you shouldn't be running as they are out of security maintenance: 在较旧的版本中,由于安全性太高,您不应该运行它们:

$results = $test->results();
print_r($results['second']);

Edit: The first example originally said 5.6 and above but array dereferencing was introduced in 5.4! 编辑:第一个示例最初表示5.6及更高版本,但在5.4中引入了数组解引用! For the avoidance of doubt, 5.6 is the lowest php version within security maintenance. 为避免疑问,5.6是安全维护中最低的php版本。

In PHP an array value can be dereferenced from the array by its key. 在PHP中,可以通过键从数组中取消引用数组值。

$arr = ["foo" => "bar", "baz" => "quix"];

echo $arr["foo"]; // gives us "bar"
echo $arr["baz"]; // gives us "quix"

If the method/function returns an array the same can be done with the return value, whether by assigning the return value to a variable and using the variable to dereference the value by key, or by using function array dereferencing . 如果该方法/函数返回一个数组,则可以使用返回值来完成此操作,无论是通过将返回值分配给变量并使用该变量通过键来取消引用该值,还是通过使用函数数组解引用

class Test {

    public function results() {

      return ["foo" => "bar", "baz" => "quix"];

    }     

}

$test = new Test;

$arr = $test->results();
echo $arr["foo"]; // gives us "bar"
echo $arr["baz"]; // gives us "quix"

// Using FAD (Function Array Dereferencing)

echo $test->results()["foo"]; // gives us "bar"
echo $test->results()["baz"]; // gives us "quix"

Of course there are two important caveats to using function array dereferencing. 当然,使用函数数组取消引用有两个重要警告。

  1. The function is executed each time you do it ( ie no memoziation ) 每次执行该函数都会执行一次( 即没有记忆
  2. If the key does not exist or the function returns something other than array, you get an error 如果键不存在或函数返回数组以外的内容,则会出现错误

Which means it's usually safer to rely on assigning the return value to a variable first and then doing your validation there for safety... Unless you are sure the function will always return an array with that key and you know you won't need to reuse the array. 这意味着通常更安全的方法是先将返回值分配给变量,然后再在那里进行安全性验证...除非您确定函数将始终返回带有该键的数组,并且您知道不需要重用数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM