【问题标题】:Returning elements from an array nest based on criteria根据条件从数组嵌套中返回元素
【发布时间】:2019-08-21 21:28:37
【问题描述】:

我正在尝试在数组中搜索元素(在本例中为“电子”),然后返回嵌套值。

我正在使用的数组

array:2 [▼
  0 => array:2 [▼
    "value" => "0241-6230"
    "type" => "print"
  ]
  1 => array:2 [▼
    "value" => "2339-1623"
    "type" => "electronic"
  ]
]

下面是我正在使用的代码。

<?php

$this->doi = 'anydoinumber';
$this->client = new Client();
$this->Url = 'https://api.crossref.org/works/:'.$this->doi;
$res = $this->client->get($this->Url);
$decoded_items = json_decode($res->getBody(), true);

if (isset($decoded_items['message']['issn-type'])) {
    $this->issn = '';
} else {
    // no electronic ISSN given
    Log.Alert('No electronic ISSN for :'.$this->Doi);
}

我期待的输出

$this->issn = "2339-1623"

【问题讨论】:

  • 请您显示您拥有的代码和您期望的输出示例吗?
  • 请您将其添加到您的问题中,而不是将其放入 cmets :)

标签: php arrays laravel


【解决方案1】:

PHP方式:

$searchingFor = 'electronic';
$filteredArray = array_filter($initialArray, function($v, $k) use ($searchingFor) {
    return $searchingFor === $v['type'];
}, ARRAY_FILTER_USE_BOTH);

//var_dump($filteredArray);

Docs.

【讨论】:

    【解决方案2】:

    您必须使用foreach 循环

    $searchterm = 'electronics';
    foreach($nested as $key => $value) {
      if($value['type'] == $searchterm) {
        return $value['value'];
        break;
      }
    }
    

    【讨论】:

      【解决方案3】:

      你可以使用 laravel 集合:

      collect($array)->where('type', 'electronic')->first();
      

      输出是:

      array:2 [
        "value" => "2339-1623"
        "type" => "electronic"
      ]
      

      【讨论】:

      • 你可以阅读 Laravel 集合here
      • @user5067291 也许您需要get() 而不是first()?请澄清。
      • 如果您需要多个集合对象,请使用 get()。但是,如果您想从集合中获取单个对象,请使用 first()。
      【解决方案4】:

      您可以使用简单的 foreach 循环将匹配的元素添加到结果数组中

      $filtered = [];
      foreach($myarr as $i){
          if($i['type'] == 'searched type')
              $filtered[] = $i;
      }
      
      

      或者你可以在遇到给定类型的第一个元素时跳出循环

      foreach($myarr as $i){
          if($i['type'] == 'searched type')
              return $i; // or $found = $i and then break;
      }
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-13
        • 2020-05-30
        • 2018-10-17
        • 2018-05-17
        • 2016-04-28
        • 1970-01-01
        • 1970-01-01
        • 2018-08-16
        相关资源
        最近更新 更多