I am trying to build a dynamic array for a 3rd party shipping software. It would an array with package information for each box we're shipping through UPS. I had it working earlier or, I thought I did.

Here is an example of an success for call where is parcel element is a new box.

"from_address" => $from_address_params,
		    "to_address" => $to_address_params,
		    "shipments" => array(
		        array(
		            "parcel" => array("length" => null, "width" => null, "height" => null, "weight" => 12)
		        ),
		        array(
		            "parcel" => array("length" => null, "width" => null, "height" => null, "weight" => 13)
		        ),
		    ),

That works fine and return the correct rates base on multiple boxes.

Here is how I am trying to build this array.

$arr = ''; 
		for($i=0; $i<$numBoxes; $i++){

	    $arr .= '"parcel" => array("length" => null, "width" => null, "height" => null, "weight" => '.$indiBoxW.')';
	    
	    if($i + 1 < $numBoxes){
	        $arr .= ', ';
	    }
	    else{
	        $arr .= '';
	    }
	}

Then add that array like this:

"from_address" => $from_address_params,
		    "to_address" => $to_address_params,
		    "shipments" => array(
		        $arr
		    ),
		));

    You maybe could do something like that using eval() to turn what is just a string that looks like an array definition into something that would actually become an array definition; but as the saying goes, "If eval() is the answer, you're probably asking the wrong question."

    I think what you want to do in that for() loop is to actually build an array that you could then add to the "parent" array. Maybe something like this (with me hopefully not having entirely misconstrued the desired array structure):

    $arr = []; 
    for($i=0; $i<$numBoxes; $i++){
        $arr[] = [
            "parcel" => [
                "length" => null,
                "width" => null,
                "height" => null,
                "weight" => $indiBoxW
            ]
        ];
    }
    
    // later...
    $something = [
        "from_address" => $from_address_params,
        "to_address" => $to_address_params,
        "shipments" => $arr
    ];
    
      Write a Reply...