Amit Sharma
Amit Sharma

Reputation: 1795

value is not inserting into array properly

It is correctly insert the value of $name[$init] into the key dsf under the $val['dsf'] but it is inerting only the last value in dsf under the $val['customProduct']['dsf']

$name = array(0=>'Amit',1=>'Amit1',2=>'Amit2');
foreach($order->orderLines as $init =>$val){
        $val['dsf'] = $name[$init];
        $val['customProduct']['dsf'] = $name[$init];
}

Upvotes: 1

Views: 94

Answers (2)

Harshil Kaneria
Harshil Kaneria

Reputation: 153

Please Try This and In Case If You Have Any Query Just Comment I Am Happy To Answer

<?php

$name = array(0=>'Amit',1=>'Amit1',2=>'Amit2');


$orderLines = array(
    array(
        "id"=>1,
        "order_id"=>10,
        "dfs"=>0,
        "customProduct"=>array(
            "id"=>102,
            "order_id"=>10,
            "dfs"=>0,
            "name"=>""
        )
    ),
    array(
        "id"=>2,
        "order_id"=>20,
        "dfs"=>1,
        "customProduct"=>array(
            "id"=>105,
            "order_id"=>20,
            "dfs"=>1,
            "name"=>""
        )
    ),
    array(
        "id"=>3,
        "order_id"=>50,
        "dfs"=>2,
        "customProduct"=>array(
            "id"=>107,
            "order_id"=>50,
            "dfs"=>2,
            "name"=>""
        )
    )
);

$orderLinestemp = array();
foreach($name as $value){
    
    $temp_array = array("dfs"=>$value,"customProduct"=>array("name"=>$value));
    array_push($orderLinestemp, $temp_array);
}

$orderLines=array_replace_recursive($orderLines,$orderLinestemp);

echo "<pre/>";

print_r($orderLines);

?>

output

enter image description here

Upvotes: 1

Dmitry Leiko
Dmitry Leiko

Reputation: 4412

You need the $val pass by reference:

$name = array(0=>'Amit',1=>'Amit1',2=>'Amit2');
$orderLines = array(
    array(
        'dsf' => array(),
        'customProduct' => array()
    ),
    array(
        'dsf' => array(),
        'customProduct' => array()
    ),
    array(
        'dsf' => array(),
        'customProduct' => array()
    ),
);
foreach($orderLines as $init => &$val){ //edit here
    $val['dsf']= $name[$init];
    $val['customProduct']['dsf'] = $name[$init];
}

print_r($orderLines);

Output:

Array
(
    [0] => Array
        (
            [dsf] => Amit
            [customProduct] => Array
                (
                    [dsf] => Amit
                )

        )

    [1] => Array
        (
            [dsf] => Amit1
            [customProduct] => Array
                (
                    [dsf] => Amit1
                )

        )

    [2] => Array
        (
            [dsf] => Amit2
            [customProduct] => Array
                (
                    [dsf] => Amit2
                )

        )

)

See here

Upvotes: 1

Related Questions