PHP – How to increase asscociative array index inside foreach

My requested input is in $journal. It contains three arrays accounts_ledger_id, debit, credit and among which arrays are associative arrays. What do I want to input into two static arrays that have the same index at the associative level?

Inside journal:

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"
  ]
]

This what I tried with:

$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++;
}

Output:

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"
  ]
]

I want the output as:

  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"
      ]
    ]

>Solution :

Looks like you’re trying to add two additional arrays, "accounts_project_id" and "accounts_voucher_id", to the $journal array, and you want these arrays to have the same number of indices as the other arrays in $journal, with the same index values.

Here’s one way you could update your code to achieve this:

$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;
}

Leave a Reply