【问题标题】:how to echo a specific value in array if key is not specified?如果未指定键,如何在数组中回显特定值?
【发布时间】:2016-09-17 20:50:03
【问题描述】:
class database {
public function dataarray() {
$array = array('John', 'Alex', 'Smith','Doe','Mane','Rio');
   }
}
$export = new database();
echo $export->dataarray(); // ??? what echo code/ other style code, to show only name 'John' value.

我只想回显上面 $array 的“值”(John)。如果未指定密钥,我该如何实现?有可能吗?

【问题讨论】:

  • 你需要从方法中返回你的数据。然后你就可以访问你想要的索引了。
  • 为什么这个问题两次被否决?

标签: php arrays


【解决方案1】:
class database { 
public function dataarray($index) { 
$array = array('John', 'Alex', 'Smith','Doe','Mane','Rio'); 
return $array[$index]; } 
} 
$export = new database(); 
echo $export->dataarray(0);

我会在函数中传递一个参数并让它返回索引值,就像这样。

【讨论】:

    【解决方案2】:
    class database {
    public function dataarray() {
        $array = array('John', 'Alex', 'Smith','Doe','Mane','Rio');
        return $array;
       }
    }
    
    $export = new database();
    
    echo $export->dataarray()[0];
    

    【讨论】:

    • 不客气,但 Ben Edwards 可能更好。
    猜你喜欢
    • 2018-10-02
    • 2020-02-10
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多