我有一个我正在预告的数组:
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)才能正确访问这些属性?
答案 0 :(得分: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];
}
}