0

I have this code:

...............................................
               'Detalle' => array()
    ];


foreach ($cart as $line => $item) {

//check condition
if (strtolower($item['description']) === 'something') {
    $cond = true;
} else {
    $cond= false;
}

$ab['Detalle'][]=array(     

    'NmbItem' => $item['name'],
    'QtyItem' => (int)$item['quantity'],
    'PrcItem' => $item['price']     

);

if ($cond){
     $array2 = array('IndExe' => 1);
     array_merge($ab['Detalle'],$array2);
}

}

How can I add 'IndExe' to $ab['Detalle'] array only when the condition is true? I tried array_merge, array_merge_recursive but nothing.

IndExe only can be 1, another value like 0 or null is not possible. I tried:

  $ab['Detalle'][]=array(        

        'NmbItem' => $item['name'],
        'QtyItem' => (int)$item['quantity'],
        'PrcItem' => $item['price']   
        'IndExe' => ($cond? 1 : 0 )     

    );

but when cond = false then IndExe = 0, is not what I need. IndExe must be added only when cond = true.

0

2 Answers 2

3

Let's introduce a temporary array:

$tempArray=Array(     
    'NmbItem' => $item['name'],
    'QtyItem' => (int)$item['quantity'],
    'PrcItem' => $item['price']   
);

if ($cond){
     $tempArray['IndExe'] = 1;
}

$ab['Detalle'][] = $tempArray;
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is the dynamically appended [] element. You could use the index $line:

foreach ($cart as $line => $item) {

    $ab['Detalle'][$line] = array(
        'NmbItem' => $item['name'],
        'QtyItem' => (int)$item['quantity'],
        'PrcItem' => $item['price']     
    );    
    if (strtolower($item['description']) === 'something') {
        $ab['Detalle'][$line]['IndExe'] = 1;
    }
}

If $line doesn't give the indexes you want (but they shouldn't matter), then:

$ab['Detalle'] = array_values($ab['Detalle']);

Unless you're using $cond again later in the code, you don't need it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.