Php array not working. whats wrong? - php

I want to work with api.
Here is my code:
// create a new purchase bill
$purchase = $parasut->make('sale')->create(array (
'description' => $siparis,
'invoice_id' => null,
'invoice_series' => null,
'currency' => 'TRL',
'item_type' => 'invoice',
'issue_date' => $order_date_created,
'due_date' => $order_date_created,
'contact_id' => $contactToken,
'category_id' => null,
'archived' => false,
'billing_address' => $user_address,
'billing_fax' => null,
'billing_phone' => $user_phone,
'details_attributes' => array (
$parasut->make('product')->getProductFromOrder(), // the products
),
));
Here is getProductFromOrder() function:
public function getProductFromOrder()
{
$sku = array(5542003,5542004);
$qty = array("3","1");
$total = array("11.29","12.00");
for($i=0; $i<count($sku); $i++){
$urunler[$i] = array(
'product_id' => $sku[$i], // the products
'quantity' => '3',
'unit_price' => '12.99',
'vat_rate' => '18',
'discount_type' => 'amount',
'discount_value' => '0',
);
print ($urunler[$i]);
}
}
Its not working. When i run the first code, products not showing. Where is the mistake?
Thanks in advance for help.

Change the function getProductFromOrder() to this instead:
public function getProductFromOrder()
{
$sku = array(5542003,5542004);
$qty = array("3","1");
$total = array("11.29","12.00");
for($i=0; $i<count($sku); $i++){
$urunler[$i] = array(
'product_id' => $sku[$i], // the products
'quantity' => '3',
'unit_price' => '12.99',
'vat_rate' => '18',
'discount_type' => 'amount',
'discount_value' => '0',
);
}
return $urunler;
}
Use return instead of print and write the return outside the for loop.

Related

Create Array From Key

Thank you in advance. Is there any way to create a multidimensional array from key names.
$array = array(
'brand/name' => 'BRAND_NAME',
'brand/model' => 'MODEL_NO',
'brand/inv/qty' => '20',
'brand/inv/cost' => '30',
'wh' => 'NY',
'brand/inv/sales' => '40'
);
Transform to this array.
$array = array(
'brand' => array(
'name' => 'BRAND_NAME',
'model' => 'MODEL_NO',
'inv' => array(
'qty' => 20,
'cost' => 30,
'sales' => 40,
)
),
'wh' => 'NY'
);
Thank you !
Try my code (I used the reference operator "&" to get the successive inner arrays):
Input array:
$array = array(
'brand/name' => 'BRAND_NAME',
'brand/model' => 'MODEL_NO',
'brand/inv/qty' => '20',
'brand/inv/cost' => '30',
'wh' => 'NY',
'brand/inv/sales' => '40'
);
php code:
<?php
$resultArray = array();
foreach($array as $path => $element) {
$pathArray = explode("/", $path);
$auxRef = &$resultArray;
foreach($pathArray as $pathPart) {
if(! array_key_exists($pathPart, $auxRef)) {
$auxRef[$pathPart] = array();
}
$auxRef = &$auxRef[$pathPart];
}
$auxRef = $element;
unset($auxRef);
}
?>
Result array:
array ( 'brand' => array ( 'name' => 'BRAND_NAME', 'model' => 'MODEL_NO', 'inv' => array ( 'qty' => '20', 'cost' => '30', 'sales' => '40', ), ), 'wh' => 'NY', )

Add array in exiting array in php

I have a json. First i have to decode then add loop on a specific key of json.
public function saveRecode() {
$json ='{"productID":"1","productPrice":"5585.00","productDetails":{"productImage":"https:\/\/development.modeconfigurator.com\/eCommerce\/backdrop.jpg","TABLE TOP":"COPPER DISTRESSED","TABLE FRAME":"RAL 5024 PASTEL BLUE"},"_":"1583172411557"}';
$jsonDecode = json_decode($json, true);
foreach ($jsonDecode["productDetails"] as $key => $value) {
$options = [
'0' => [
'sort_order' => '1',
'title' => $key,
'price_type' => 'fixed',
'price' => '',
'type' => 'drop_down',
'is_require' => '0',
'values' => [
'0' =>[
'title' => $value,
'price' => '',
'price_type' => 'fixed',
'sku' => '',
'sort_order' => '0',
'is_delete' => '0',
]
]
]
];
}
foreach ($options as $arrayOption) {
$this->_logger->debug("enter in opt ");
$this->_logger->info(print_r($arrayOption,true));
$option = $this->_options
->setProductId($_product->getId())
->setStoreId($_product->getStoreId())
->addData($arrayOption);
$option->save();
$_product->addOption($option);
}
}
In database only last recode save. But i want to save all parameters please take a loop.
You're replacing $options each time through the loop, not adding a new element to it. It should be:
$options = [];
foreach ($jsonDecode["productDetails"] as $key => $value) {
$options[] = [
'sort_order' => '1',
'title' => $key,
'price_type' => 'fixed',
'price' => '',
'type' => 'drop_down',
'is_require' => '0',
'values' => [
'0' =>[
'title' => $value,
'price' => '',
'price_type' => 'fixed',
'sku' => '',
'sort_order' => '0',
'is_delete' => '0',
]
]
];
}

mongo php library updateOne & insertOne damaging collection

I have an application I am trying to update from legacy to new driver. I am having a problem with collections being damaged when the below code is triggered. I think I have narrowed it down here.
function update($collection,$criteria,$data,$insertIfNotExists = false)
{
if(!empty($collection) && !empty($criteria) && !empty($data)) {
if (!isset($this->collection[$collection])) {
$this->collection[$collection] = (new MongoDB\Client)->hebe->{$collection};
}
if ($insertIfNotExists) {
$oldData = $this->collection[$collection]->findOne($criteria);
if ($oldData == NULL) {
$data['createdDate'] = date("Y-m-d H:i:s");
$data['modifiedDate'] = (isset($data['modifiedDate'])) ? $data['modifiedDate']:date("Y-m-d H:i:s");
/*
return ($this->collection[$collection]->insertOne($data)) ? array('status'=>'ok'):array('status'=>'error','error'=>'unknown_error');
*/
} else {
$newData = $oldData;
foreach($data as $n=>$v) {
$newData[$n] = $v;
}
$newData['modifiedDate'] = (isset($newData['modifiedDate'])) ? $newData['modifiedDate']:date("Y-m-d H:i:s");
/*
return ($this->collection[$collection]->updateOne($criteria,['$set' => $newData])) ? array('status'=>'ok'):array('status'=>'error','error'=>'unknown_error');
*/
}
} else {
/*
return ($this->collection[$collection]->updateOne($criteria,['$set' => $data])) ? array('status'=>'ok'):array('status'=>'error','error'=>'unknown_error');
*/
}
}
}
example variables are
$collection = 'customer'
$criteria = array ( 'number' => '9999',)
$data = array (
'number' => '9999',
'name' => 'Testing Account',
'reference' => 'Peter Smith',
'defaultDeliveryAddress' => 1,
'visitAddress' => '',
'address' => '',
'district' => 'Marknad',
'postAddress' => '',
'orgNumber' => '5562041771',
'phone' => '031-7802700',
'fax' => '031-193328',
'groupCode' => 'int',
'creditCustomer' => '',
'typeOfDelivery' => 'Bil',
'typeOfPayment' => '10',
'emailAddresses' =>
array (
'invoice' => 'email1#domain.com',
'order' => 'email2#domain.com',
'deliveryNote' => 'email3#domain.com',
'packingSlip' => 'email4#domain.com',
),
'orderType' => NULL,
'termsOfDelivery' => 'RC',
'creditLimit' => 100000.0,
'pricelist' => 4,
'pricelist1' => '',
'pricelist2' => '9998',
'pricelist3' => '104',
'discount' => NULL,
'countryCode' => 'SE',
'currencyCode' => 'SEK',
'blocked' => 0,
'deliveryCost' => 0,
'vatCode' => '2',
'email' => 'peremail#domain.com',
'password' => 'password',
'modifiedDate' => '2019-06-25 00:00:00',
'deliveryAddresses' =>
array (
0 =>
array (
'row' => 1,
'name' => 'Test Address',
'address' => 'Box 12345',
'postAddress' => '42246',
'default' => true,
),
1 =>
array (
'number' => '9999',
'name' => 'Testing Address',
'reference' => '13232',
'address' => 'Box 12245',
'postAddress' => '42246',
),
),
'references' =>
array (
0 =>
array (
'number' => '9999',
'name' => 'Testing',
'email' => '',
'password' => '',
),
1 =>
array (
'number' => '9999',
'name' => 'Testing2',
'email' => '',
'password' => 'password',
),
2 =>
array (
'number' => '9999',
'name' => 'Peter Smith',
'email' => '',
'password' => 'password',
),
),
)
Can someone point me in the right direction on what I am doing wrong with updateOne and insertOne. From what I understand by the docs is it supports array.
EDIT: a little background is I upgraded this system and MongoDB from 2.6 to 3.6. I also upgraded mongodb driver from legacy mongo.
The problem was the old data in the collection had quotations and the updateOne/insertOne data did not. Correcting this seem to solve the problem.

add a default value to an array

I have the following code in my opencart product.php control file.
$product_option_value_data = array();
foreach ($product_option['product_option_value'] as $product_option_value) {
$product_option_value_data[] = array(
'product_option_value_id' => $product_option_value['product_option_value_id'],
'option_value_id' => $product_option_value['option_value_id'],
'quantity' => isset ($product_option_value['quantity']) ? $product_option_value['quantity'] : '1',
'subtract' => $product_option_value['subtract'],
'price' => isset ($product_option_value['price'])? $product_option_value['price'] : '27.99',
'price_prefix' => $product_option_value['price_prefix'],
'points' => $product_option_value['points'],
'points_prefix' => $product_option_value['points_prefix'],
'weight' => $product_option_value['weight'],
'weight_prefix' => $product_option_value['weight_prefix']
);
}
I need to add default value to quantity, price, subtract.
Any help will be highly appreciated.
You are almost there. You have done that for two of your elements. Just add the same check for the subtract one.
$product_option_value_data = array();
foreach ($product_option['product_option_value'] as $product_option_value) {
$product_option_value_data[] = array(
'product_option_value_id' => $product_option_value['product_option_value_id'],
'option_value_id' => $product_option_value['option_value_id'],
'quantity' =>
isset ($product_option_value['quantity']) ?
$product_option_value['quantity'] :
'1', // THE DEFAULT FOR QUANTITY
'subtract' =>
isset ($product_option_value['subtract']) ?
$product_option_value['subtract'] :
'22', // THE DEFAULT FOR SUBTRACK
'price' =>
isset ($product_option_value['price']) ?
$product_option_value['price'] :
'27.99', //THE DEFAULT FOR PRICE
'price_prefix' => $product_option_value['price_prefix'],
'points' => $product_option_value['points'],
'points_prefix' => $product_option_value['points_prefix'],
'weight' => $product_option_value['weight'],
'weight_prefix' => $product_option_value['weight_prefix']
);
}
Hope this helps

Printing all array results in a themable way using PHP?

I want to print all results of the taxonomy_vocabulary_11 array (this is a Drupal 7 site).
If I use <?php print render($content['taxonomy_vocabulary_11'][0]['#title']); ?> I get only one result.
I´ve usuccessfully tried
<?php foreach ($content->taxonomy_vocabulary_11 as $key => $value): $terms = $value['#title']; ?>
<?php print $terms; ?>
<?php endforeach?>
I get this error: Notice: Trying to get property of non-object
Now, this is the output I get using devel module (dpm($node);)
(object) array(
'vid' => '5178',
'uid' => '1',
'title' => 'PROYECTO',
'log' => '',
'status' => '1',
'comment' => '2',
'promote' => '0',
'sticky' => '0',
'nid' => '155',
'type' => 'jornadas',
'language' => 'und',
'created' => '1095048000',
'changed' => '1360589684',
'tnid' => '0',
'translate' => '0',
'revision_timestamp' => '1360589684',
'revision_uid' => '1',
'taxonomy_vocabulary_4' => array(),
'taxonomy_vocabulary_6' => array(
'und' => array(
array(
'tid' => '33',
'taxonomy_term' => (object) array(
'tid' => '33',
'vid' => '6',
'name' => 'Jornadas Gratuitas',
'description' => '',
'format' => NULL,
'weight' => '0',
'vocabulary_machine_name' => 'vocabulary_6',
),
),
),
),
'taxonomy_vocabulary_7' => array(
'und' => array(
array(
'tid' => '40',
'taxonomy_term' => (object) array(
'tid' => '40',
'vid' => '7',
'name' => 'Para PH',
'description' => '',
'format' => NULL,
'weight' => '-10',
'vocabulary_machine_name' => 'vocabulary_7',
),
),
),
),
'taxonomy_vocabulary_11' => array(
'und' => array(
array(
'tid' => '262',
'taxonomy_term' => (object) array(
'tid' => '262',
'vid' => '11',
'name' => 'colegios',
'description' => '',
'format' => NULL,
'weight' => '0',
'vocabulary_machine_name' => 'vocabulary_11',
),
),
array(
'tid' => '543',
'taxonomy_term' => (object) array(
'tid' => '543',
'vid' => '11',
'name' => 'derecho',
'description' => '',
'format' => NULL,
'weight' => '0',
'vocabulary_machine_name' => 'vocabulary_11',
),
),
),
),
'body' => array(
'und' => array(
array(
'value' => "
I´ve also tried <?php print render($content['taxonomy_vocabulary_11']); ?> to treat the taxonomy as any other field, but it won´t print anything.
Note: If I go and do print $content['taxonomy_vocabulary_11']; it just print the word array.
What´s wrong in my approach?
Try:
foreach ($content['taxonomy_vocabulary_11'] as $tv11) {
print render($tv11['#title']);
}
I dont use drupal but this should work if i understood how the $content['taxonomy_vocabulary_11'] array is structured.
Just in case anyone needs it:
<?php
$vid = 11; //vocabulary id
$nid = $node->nid; //it looks for the current loaded node
$query = "SELECT tid, name
FROM (
SELECT td.tid AS tid, name
FROM taxonomy_term_data AS td
JOIN taxonomy_index AS tn
ON td.tid = tn.tid
JOIN node AS n
ON n.nid = tn.nid
WHERE td.vid = ". $vid ."
AND n.status = 1
AND n.nid = ".$nid."
GROUP BY td.tid
) AS t
ORDER BY name ASC";
$result = db_query($query);
foreach($result as $term) {
echo l($term->name, "taxonomy/term/$term->tid") . ', ';
}
?>

Categories