Here is the array, which I have posted through Ajax and get into the ajax.php file. Now i want to add a new array, as shown below.
Array
(
[0] => Array
(
[contact_id] => 5000
[invoice] => 476
)
[1] => Array
(
[contact_id] => 5000
[invoice] => 396
)
[2] => Array
(
[contact_id] => 1490
[invoice] => 1083
)
[3] => Array
(
[contact_id] => 1490
[invoice] => 498
)
)
I also want to add this if contact id are same, then invoice will be added
Array
(
[0] => Array
(
[contact_id] => 5000
[invoice] => Array (
[0] =>476,
[1] =>396
)
)
[2] => Array
(
[contact_id] => 1490
[invoice] => Array (
[0] =>1083,
[1] =>498
)
)
)
I tried to do it, without success. Here is my code:
$invtemp =array();
foreach($_POST['invoice_id'] as $value){
if(!in_array($value['contact_id'], $invtemp, true)){
$arr = array($value['contact_id'] => $value['invoice'] );
array_push($invtemp, $arr);
}
}
I think you can achieve with simple foreach
:
foreach ($array as $value) {
$arr[$value['contact_id']]['contact_id'] = $value['contact_id'];
$arr[$value['contact_id']]['invoice'][] = $value['invoice'];
}
print_r($arr);
This provides:
Array
(
[5000] => Array
(
[contact_id] => 5000
[invoice] => Array
(
[0] => 476
[1] => 396
)
)
[1490] => Array
(
[contact_id] => 1490
[invoice] => Array
(
[0] => 1083
[1] => 498
)
)
)
To reset the keys:
print_r(array_values($arr));
Not so important, but to make it cleaner, you can use extract
:
foreach ($array as $value) {
extract($value);
$arr[$contact_id]['contact_id'] = $contact_id;
$arr[$contact_id]['invoice'][] = $invoice;
}
print_r($arr);
Plain and simple.
$invtemp = array();
foreach($_POST['invoice_id'] as $value){
$invtemp[$value['contact_id']]['invoice'][] = $value['invoice'];
}
By indexing your array by contact_id, you ensures yourself that there is only one subarray for each contact_id.
By adding each new invoice as a new index, you ensure yourself that each invoice is added to your final array even there are already invoices associted with the contact_id.
And since your keys are the contact_ids, you don't need to store them as values to have them available.
This will create an array similar to what you want but with the key as contact_id.
It creates a slightly more compact array that will still be easy to use.
$arr = array
(
Array
(
"contact_id" => 5000,
'invoice' => 476
),
Array
(
'contact_id' => 5000,
'invoice' => 396
),
Array
(
'contact_id' => 1490,
'invoice' => 1083
),
Array
(
'contact_id' => 1490,
'invoice' => 498
));
$res =array();
Foreach($arr as $subarr){
Foreach($subarr as $key => $val){
If($key == "contact_id") {
If(!isset($res[$val])) $res[$val] = array();
$cid = $val;
}Else{
$res[$cid][]= $val;
}
}
}
Var_dump($res);
Outputs:
array(2) {
[5000]=>
array(2) {
[0]=> int(476)
[1]=> int(396)
}
[1490]=>
array(2) {
[0]=> int(1083)
[1]=> int(498)
}
}
See here: https://3v4l.org/cmH8P