laravel PHP -如何在foreach中增加关联数组索引[已关闭]

polhcujo  于 2023-01-18  发布在  PHP
关注(0)|答案(2)|浏览(117)

8小时前关门了。
Improve this question
我请求的输入是$journal。它包含三个数组accounts_ledger_iddebitcredit,其中数组是关联数组。我想在两个静态数组中输入什么,这两个静态数组在关联层具有相同的索引?

    • 内部日志:**
array:4 [▼
  "_token" => "y7euU2ocmiwCbni0o6JAtZINnnkmDf2pnfvt1Hvf"
  "accounts_ledger_id" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "debit" => array:2 [▼
    0 => "100"
    1 => null
  ]
  "credit" => array:2 [▼
    0 => null
    1 => "100"
  ]
]
    • 这就是我尝试的**
$data = array();
$i = 0;
foreach($journal as $key => $val){
   $data[$key]= $val;
   $data['accounts_project_id'][$i] = Session::get('project.name');
   $data['accounts_voucher_id'][$i] = 1;
   $i++;
}
    • 输出:**
array:6 [▼
  "_token" => "y7euU2ocmiwCbni0o6JAtZINnnkmDf2pnfvt1Hvf"
  "accounts_project_id" => array:1 [▼
    0 => "1"
    1 => "1"
    2 => "1"
    3 => "1"
  ]
  "accounts_voucher_id" => array:1 [▼
    0 => 1
    1 => 1
    2 => 1
    3 => 1
  ]
  "accounts_ledger_id" => array:2 [▼
    0 => "1"
    1 => "2"
  ]
  "debit" => array:2 [▼
    0 => "100"
    1 => null
  ]
  "credit" => array:2 [▼
    0 => null
    1 => "100"
  ]
]
    • 我希望输出为:**
array:6 [▼
      "_token" => "y7euU2ocmiwCbni0o6JAtZINnnkmDf2pnfvt1Hvf"
      "accounts_project_id" => array:1 [▼
        0 => "1"
        1 => "1"
      ]
      "accounts_voucher_id" => array:1 [▼
        0 => "1"
        1 => "1"
      ]
      "accounts_ledger_id" => array:2 [▼
        0 => "1"
        1 => "2"
      ]
      "debit" => array:2 [▼
        0 => "100"
        1 => null
      ]
      "credit" => array:2 [▼
        0 => null
        1 => "100"
      ]
    ]
vojdkbi0

vojdkbi01#

看起来您正尝试向$journal数组添加两个额外的数组“accounts_project_id”和“accounts_voucher_id”,并且您希望这些数组与$journal中的其他数组具有相同的索引数和索引值。
以下是更新代码以实现此目的的一种方法:

$data = array();

foreach($journal as $key => $val){
   $data[$key]= $val;
}
foreach($data['accounts_ledger_id'] as $key => $val){
    $data['accounts_project_id'][$key] = Session::get('project.name');
    $data['accounts_voucher_id'][$key] = 1;
}
axzmvihb

axzmvihb2#

如果我没理解错你的问题,你需要做以下事情:

$data = $journal;
$data['accounts_project_id'] = [
  Session::get('project.name'), 
  Session::get('project.name')
];
$data['accounts_voucher_id'] = [
  "1", 
  "1"
];

相关问题