【问题标题】:PHP accessing property inside multi-dimensional array, which has an outer arrayPHP访问多维数组内的属性,该数组有一个外部数组
【发布时间】:2018-03-12 15:30:04
【问题描述】:

我有一个数组要遍历:

array:8132 [
  0 => {#551
  "address_id": "94e224af-135f-af31-3619-535acfae9930"
  "fiber_phase": "101"
  "parsed_hash": "1bc7fb114ee10d7cb9cea10693d238b5"
  "min_number": 400
  "max_number": 499
  "sales_rep": "164"
  "id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38"
  "name": "48TH ST E"
  "block_minimum": 400
  "block_maximum": 498
}

在 foreach 中,我有另一个数组,我需要访问 if 语句的某些属性,然后将新属性添加到原始数组 ($data):

foreach ($data as $phase) {
        $all_phases = EmeraldFiber::getPhases();
        dd($all_phases);

        if ($phase->fiber_phase === $all_phases[1]['name']) {
            $phase->fiber_status = $all_phases[1]['fiber_status'];
        }
        return $data;
    }

dd($all_phases); 看起来像这样:

array:270 [
  1 => array:7 [
    "id" => "10bc06d0-05de-07e2-b2de-5214fba5045a"
    "name" => "1"
    "description" => "50th France"
    "encoded_points" => "_sbqGnesxPJwv@iJBKpv@fJ@"
    "fiber_status" => "Live"
    "status_date" => "2010-09-01 00:00:00"

]

使用上面的 foreach,我只返回原始数组,没有新属性 fiber_status。我没有正确返回它吗?或者我是否需要映射第二个数组 ($all_phases) 才能正确访问这些属性?

【问题讨论】:

  • 使用参考foreach ($data as &$phase)
  • $all_phases = EmeraldFiber::getPhases(); 不依赖于$phase。它应该留在foreach之外。
  • 在 1 次迭代后,您的返回将有效地阻止 for each
  • 我想name=1 不等于phase_fiber=101
  • $phase->fiber_phase === $all_phases[1]['name'] 有很多匹配项

标签: php arrays multidimensional-array foreach


【解决方案1】:

我想你不需要return 任何东西:

// receive object once instead receiving of it multiple times
$all_phases = EmeraldFiber::getPhases();
// extract required values
$phase_name = $all_phases[1]['name'];
$phase_status = $all_phases[1]['fiber_status'];

foreach ($data as $phase) {
    if ($phase->fiber_phase === $phase_name) {
        $phase->fiber_status = $phase_status;
    }
}

// if you have this code in a function - return data here
// otherwise - you don't need return
// return $data;

更新: 如果$all_phases 是具有所有可用阶段的数组,并且您需要检查$phase->fiber_phase 是否在其中,那么您应该执行以下操作:

// receive object once instead receiving of it multiple times
$all_phases = EmeraldFiber::getPhases();
// create pairs
$phase_names = [];        
foreach ($all_phases as $item) {
    $phase_names[$item['name']] = $item['fiber_status'];
}

foreach ($data as $phase) {
    // check if `$phase->fiber_phase` exists in `$phase_names`
    if (isset($phase_names[$phase->fiber_phase])) {
        // if it does - add it's value to `$phase` object
        $phase->fiber_status = $phase_names[$phase->fiber_phase];
    }
}

【讨论】:

  • 该确切代码返回原始数组,不受影响:/
  • $phase 是数组还是对象?添加调试 - 检查变量的值,确保在某处满足if 条件。
  • $phase 是一个对象
  • 澄清一下,原始 $data 数组中有很多 phase_name 匹配项,如果存在 phase_name/fiber_phase 匹配,我会尝试将 Fiber_status 属性注入 $data 数组。跨度>
  • 你调试了吗?你确定你的ifstatement 满足了吗?
猜你喜欢
  • 2018-05-19
  • 2016-10-28
  • 2020-08-17
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 2019-06-13
相关资源
最近更新 更多