根据条件从数组嵌套返回元素

时间:2019-03-31 16:11:48

标签: php arrays laravel

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

我正在使用的数组

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"

4 个答案:

答案 0 :(得分:6)

您可以使用laravel集合:

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

输出为:

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

答案 1 :(得分:0)

您可以使用简单的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;
}

答案 2 :(得分:-1)

您必须使用foreach循环

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

答案 3 :(得分:-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

相关问题