Can any conditional operators be used with an element while defining a multidimensional array?
-
14-04-2021 - |
Pregunta
While building a multi-dimensional array as shown below, I need to use a loop to retrieve some value from $this_fulfillment_record
to be assigned to "amount" =>
. Can a if statement be used while defining the array "[trackingInfo]" => array(
If so, please show me an example.
// Array to be built to match JSON structure.
$fulfillment_array['orderShipment']['orderLines']['orderLine'] = [];
foreach ($fulfillment_records as $this_fulfillment_record) {
// Assemble the fulfillment array for Walmart.
$fulfillment_array['orderShipment']['orderLines']['orderLine'][] = array
[trackingInfo] => Array(
[shipDateTime] => 1580821866000
[carrierName] => Array(
otherCarrier] =>
[carrier] => FedeX
)
[methodCode] => Standard
[trackingNumber] => 22344
// Can if statment be used like this?
if ($this_fulfillment_record['carrier'] == "FedeX") {
[trackingURL] => http://walmart/tracking/ups?&type=MP&seller_id=12345&promise_date=03/02/2020&dzip=92840&tracking_numbers=92345
} else {
[trackingURL] => =""
}
)
Solución
You can use a function/method or an array_map to define the content on an attribute. For example:
// Array to be built to match JSON structure.
$amount_values = [1, 2, 3]; // some sample amount values to interact
$fulfillment_array['orderShipment']['orderLines']['orderLine'] = [];
foreach ($fulfillment_records as $this_fulfillment_record) {
// Assemble the fulfillment array for Walmart.
$fulfillment_array['orderShipment']['orderLines']['orderLine'][] = array(
"status" => "Shipped",
"statusQuantity" => array(
"unitOfMeasurement" => "Each",
// interact with some other value
"amount" => array_map(
function(value) {
// do your logic/interaction here as a normal method to prepare the content to be set
return value_to_be_set;
},
$amount_values
)
)
);
Or, you can use an anonymous function If you need to process an return a content that is very specific:
// Array to be built to match JSON structure.
$interactor = function($yourParameter) {
// do your code interaction here
return $value_to_be_returned;
};
$fulfillment_array['orderShipment']['orderLines']['orderLine'] = [];
foreach ($fulfillment_records as $this_fulfillment_record) {
// Assemble the fulfillment array for Walmart.
$fulfillment_array['orderShipment']['orderLines']['orderLine'][] = array(
"status" => "Shipped",
"statusQuantity" => array(
"unitOfMeasurement" => "Each",
// interact with some other value
"amount" => $interactor($someObjectToInteract)
)
);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange