Trying to do VLQ Base64 decoding of a LESS source map and getting odd results - source-maps

See this tutorial for context.
Here is a single source mapped line from my .css.map file: 'AILJ,CAAC,GAAgB,CAAC,EAAe,CAAC'
When I try to decode it, I'm getting negative numbers.
class VLQDecoder {
public $charToInt = [];
function __construct() {
foreach (str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=') as $i => $char) {
$this->charToInt[ $char ] = $i;
}
}
public function uRShift(int $a, int $b): int {
if ($b == 0) {
return $a;
}
return ($a >> $b) & ~(1 << (8 * PHP_INT_SIZE - 1) >> ($b - 1));
}
public function segmentToArray(string $segment): array {
$result = [];
$shift = 0;
$value = 0;
foreach (str_split($segment) as $char) {
$integer = $this->charToInt[ $char ];
$has_continuation_bit = $integer & 32;
$integer = $integer & 31;
$value += $integer << $shift;
if ($has_continuation_bit) {
$shift += 5;
} else {
$should_negate = $value & 1;
$value = $this->uRShift($value, 1);
if ($should_negate) {
$result[] = $value === 0 ? - 0x80000000 : $value * - 1;
} else {
$result[] = $value;
}
$value = $shift = 0;
}
}
return $result;
}
}
$VLQDecoder = new VLQDecoder();
$mappings = ['AILJ,CAAC,GAAgB,CAAC,EAAe,CAAC'];
foreach ($mappings as $mapping) {
$segments = array_filter(explode(',', $mapping));
foreach ($segments as $segment) {
$array = $VLQDecoder->segmentToArray($segment);
var_dump([$segment=>$array]);
}
}
This outputs:
array(1) {
["AILJ"]=>
array(4) {
[0]=>
int(0)
[1]=>
int(4)
[2]=>
int(-5)
[3]=>
int(-4)
}
}
array(1) {
["CAAC"]=>
array(4) {
[0]=>
int(1)
[1]=>
int(0)
[2]=>
int(0)
[3]=>
int(1)
}
}
array(1) {
["GAAgB"]=>
array(4) {
[0]=>
int(3)
[1]=>
int(0)
[2]=>
int(0)
[3]=>
int(16)
}
}
array(1) {
["CAAC"]=>
array(4) {
[0]=>
int(1)
[1]=>
int(0)
[2]=>
int(0)
[3]=>
int(1)
}
}
array(1) {
["EAAe"]=>
array(4) {
[0]=>
int(2)
[1]=>
int(0)
[2]=>
int(0)
[3]=>
int(15)
}
}
array(1) {
["CAAC"]=>
array(4) {
[0]=>
int(1)
[1]=>
int(0)
[2]=>
int(0)
[3]=>
int(1)
}
}
The first segment has negative numbers for the row and column indexes. How is this possible?
I also don't see how any value higher than 64 is going to come out of this, yet I have hundreds of CSS files in my source map. How does that work?

Related

Fill a Tree in an multidimensional array in php

I create a Tree in an multidimensional array for my different post. A post can have one parent and now I want to be able to my tree with the different level.
Here an exemple of what I want :
array(1) {
[3258]=>
array(2) {
["post"]=>
string(30) "bank and you - publish"
["children"]=>
array(3) {
[0]=>
array(1) {
[3067]=>
array(3) {
["post"]=>
string(37) "solution - publish"
["parent"]=>
int(3258)
["children"]=>
array(1) {
[3069]=>
array(3) {
["post"]=>
string(37) "Test - publish"
["parent"]=>
int(3258)
["children"]=>
array(0) {
}
}
}
}
}
[1]=>
array(1) {
[3070]=>
array(3) {
["post"]=>
string(25) "file - publish"
["parent"]=>
int(3258)
["children"]=>
array(0) {
}
}
}
[2]=>
array(1) {
[3076]=>
array(3) {
["post"]=>
string(72) "Utils - publish"
["parent"]=>
int(3258)
["children"]=>
array(0) {
}
}
}
}
}
I have a function which can gave me all his ancestors. Which mean that when I use it, I return :
[post_parent, post_grandparent , ....]
For now I Succeed to do when my post have only 1 ancestor and I try to do for 2 or more. And this is at this moment that block for me. Because for the case of 2 ancestors I suppose to have something like :
$data[$post->ancestors[n]]['children'][$post->ancestors[n-1]]['children'][] = $item_post
And as you can imagine, more ancestors you have, more the array is complex to fill dynamically
<?php
public function process_construction( $array, $wpquery, $counter ) {
while ( $wpquery->have_posts() ) {
$post = $wpquery->post;
if ( $counter == count( $post->ancestors ) ) {
$item_post = [];
$item_post[ $post->ID ] = [
'post' => $post->post_title . ' - ' . $post->post_status,
'parent' => $post->post_parent,
'children' => [],
];
if ( $counter < 2 ) {
$array[ $post->ancestors[ $counter - 1 ] ]['children'][] = $item_post;
} else {
$this->add_item_with_multiple_ancestors( $array, $post, $item_post );
}
}
$wpquery->next_post();
}
return $array;
}
public function add_item_with_multiple_ancestors( $array, $post, $item_post ) {
for($i = count($post->ancestors)-1 ; $i => 0; $i--){
}
}
Do you have some ideas.
Thanks

What could be better way to read spreadsheet (Excel File) in laravel?

I am trying to read excel file and store that data in database. This excel file is kind of template. one would be default template and this template could be changed in future. Currently i am reading that file with many if conditions .I personally think that it isn't best way to read excel file so looking for better way.
this procedure is divided into two functions
public function importManifestFile(Request $request)
{
$path = $request->file('manifest_file')->getRealPath();
$spreadsheet = IOFactory::load($path);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
foreach ($sheetData as $rows => $ManifestConsignments) {
if ($rows >= 9 && $rows <= 37) {
$this->manifestConsignment($ManifestConsignments);
}
}
}
//import file manifest consignment function
public function manifestConsignment($ManifestConsignments)
{
$consignment = new Consignment;
foreach ($ManifestConsignments as $key => $ManifestConsignment) {
if ($key == 'A') {
}
if ($key == 'B') {
$consignment->delivery_date = $ManifestConsignment;
}
if ($key == 'C') {
$addressId = $ManifestConsignment;
}
if ($key == 'D') {
$companyName = $ManifestConsignment;
}
if ($key == 'E') {
$streetAddress = $ManifestConsignment;
}
if ($key == 'F') {
$suburb = $ManifestConsignment;
}
if ($key == 'G') {
$state = $ManifestConsignment;
}
if ($key == 'H') {
$postCode = $ManifestConsignment;
}
if (isset($postCode)) {
if (Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->exists()) {
$deliveryAddress = Address::where('company_name', $companyName)->where('street_address', $streetAddress)->where('suburb', $suburb)->where('state', $state)->where('postcode', $postCode)->first();
$deliveryAddressId = $deliveryAddress->id;
$consignment->delivery_address = $deliveryAddressId;
unset($postCode);
} else {
$address = new Address;
$address->company_name = $companyName;
$address->street_address = $streetAddress;
$address->suburb = $suburb;
$address->postcode = $postCode;
$address->state = $state;
$address->save();
$consignment->delivery_address = $address->id;
unset($postCode);
}
if ($key == 'I') {
$consignment->carton = $ManifestConsignment;
}
if ($key == 'J') {
$consignment->pallet = $ManifestConsignment;
}
if ($key == 'K') {
$consignment->weight = $ManifestConsignment;
}
if ($key == 'L') {
$consignment->invoice_value = $ManifestConsignment;
}
if ($key == 'M') {
if (!empty($ManifestConsignment)) {
$consignment->cash_on_delivery = $ManifestConsignment;
}
}
if ($key == 'N') {
$consignment->product_type_id = 1;
}
if ($key == 'O') {
$consignment->comment = $ManifestConsignment;
}
$consignment->customer_id =1;
$consignment->status = 'In Warehouse';
$consignment->product_type_id = 1;
$consignment->save();
}
}
}
$key
in code is column name of excel file . i am checking what is column name and storing data according to that.

Magento 2 - Create order programmatically and add products with custom options

Here I am using Magento 2.1.6 and trying to create order programmatically.
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Model\ProductFactory $product,
\Magento\Framework\Data\Form\FormKey $formkey,
\Magento\Quote\Model\QuoteFactory $quote,
\Magento\Quote\Model\QuoteManagement $quoteManagement,
\Magento\Customer\Model\CustomerFactory $customerFactory,
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Sales\Model\Service\OrderService $orderService,
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
\Magento\Sales\Model\Service\InvoiceService $invoiceService,
\Magento\Framework\DB\Transaction $transaction,
\Magento\Sales\Api\Data\OrderInterface $order,
\Magento\Framework\ObjectManagerInterface $objectmanager,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory,
\Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
\Magento\Quote\Api\CartManagementInterface $cartManagementInterface,
\Magento\Quote\Model\Quote\Address\Rate $shippingRate
) {
$this->_storeManager = $storeManager;
$this->_productFactory = $product;
$this->_formkey = $formkey;
$this->quote = $quote;
$this->quoteManagement = $quoteManagement;
$this->customerFactory = $customerFactory;
$this->customerRepository = $customerRepository;
$this->orderService = $orderService;
$this->_orderRepository = $orderRepository;
$this->_invoiceService = $invoiceService;
$this->_transaction = $transaction;
$this->order = $order;
$this->_objectManager = $objectmanager;
$this->productFactory = $productFactory;
$this->cartRepositoryInterface = $cartRepositoryInterface;
$this->cartManagementInterface = $cartManagementInterface;
$this->shippingRate = $shippingRate;
parent::__construct($context);
}
Create New Order Function
public function createOrderNew($orderData) {
//init the store id and website id #todo pass from array
$store = $this->_storeManager->getStore();
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
//init the customer
$customer=$this->customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($orderData['email']);// load customet by email address
//check the customer
if(!$customer->getEntityId()){
//If not avilable then create this customer
$customer->setWebsiteId($websiteId)
->setStore($store)
->setFirstname($orderData['shipping_address']['firstname'])
->setLastname($orderData['shipping_address']['lastname'])
->setEmail($orderData['email'])
->setPassword($orderData['email']);
$customer->save();
}
//init the quote
$cart_id = $this->cartManagementInterface->createEmptyCart();
$cart = $this->cartRepositoryInterface->get($cart_id);
$cart->setStore($store);
// if you have already buyer id then you can load customer directly
$customer= $this->customerRepository->getById($customer->getEntityId());
$cart->setCurrency();
$cart->assignCustomer($customer); //Assign quote to customer
$cart->save();
//add items in quote
ob_start();
foreach($orderData['items'] as $item){
foreach($item as $item) {
//echo $item['product_id'];
$product = $this->_productFactory->create()->load($item['product_id']);
$customOptions = $this->_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);
try {
// print_r($item); die();
$params = array('product' => $item['product_id'], 'qty' => $item['qty']);
if (array_key_exists('options', $item) && $item['options']) {
$params['options'] = json_decode(json_encode($item['options']), True);
}
if ($product->getTypeId() == 'configurable') {
$params['super_attribute'] = $item['super_attribute'];
} elseif ($product->getTypeId() == 'bundle') {
$params['bundle_option'] = $item['bundle_option'];
$params['bundle_option_qty'] = $item['bundle_option_qty'];
} elseif ($product->getTypeId() == 'grouped') {
$params['super_group'] = $item['super_group'];
}
$objParam = new \Magento\Framework\DataObject();
$objParam->setData($params);
$cart->addProduct($product, $objParam);
} catch (Exception $e) {
$response[$item['product_id']]= $e->getMessage();
}
unset($product);
}
}
$cart->save();
ob_flush();
$cart->getBillingAddress()->addData($orderData['shipping_address']);
$cart->getShippingAddress()->addData($orderData['shipping_address']);
// Collect Rates and Set Shipping & Payment Method
$this->shippingRate
->setCode('freeshipping_freeshipping')
->getPrice(1);
$shippingAddress = $cart->getShippingAddress();
//#todo set in order data
$shippingAddress->setCollectShippingRates(true)
->collectShippingRates()
->setShippingMethod('flatrate_flatrate'); //shipping method
//$cart->getShippingAddress()->addShippingRate($this->rate);
$cart->setPaymentMethod('checkmo'); //payment method
//#todo insert a variable to affect the invetory
$cart->setInventoryProcessed(false);
// Set sales order payment
$cart->getPayment()->importData(['method' => 'checkmo']);
// Collect total and saeve
$cart->collectTotals();
// Submit the quote and create the order
$cart->save();
$cart = $this->cartRepositoryInterface->get($cart->getId());
$order_id = $this->cartManagementInterface->placeOrder($cart->getId());
if($orderData['status'] == 4) {
return $this->createInvoice($order_id);
}
return $order_id;
}
Array Of order Details
array(5) {
["currency_id"]=>
string(3) "USD"
["email"]=>
string(16) "xxx#gmail.com"
["shipping_address"]=>
array(10) {
["firstname"]=>
string(7) "xxx"
["lastname"]=>
string(10) "xxx"
["street"]=>
string(14) "xxx"
["city"]=>
string(10) "Manchester"
["country_id"]=>
string(2) "GB"
["region"]=>
string(10) "Lancashire"
["postcode"]=>
string(7) "M23 2GF"
["telephone"]=>
string(11) "xxx"
["fax"]=>
string(0) ""
["save_in_address_book"]=>
int(1)
}
["items"]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(3) {
["product_id"]=>
string(4) "4694"
["qty"]=>
string(1) "1"
["options"]=>
array(1) {
[3658]=>
string(4) "test"
}
}
}
}
["status"]=>
string(1) "4"
}
I added Custom option for product
name: test
type: dropdown
value: test
price: $10
ID: 3658
With this code Order created successfully. Products also assigned to properly but Custom Options are not as assigned to the products.
Looking For Help.
Add custom option to product then add it to cart
$customOptions = [];
$customOptions[] = [
'label' => __('custom option title'),
'value' => 'Value',
'print_value' => 'Print Value'
];
$product->addCustomOption('additional_options', serialize($customOptions));
$cart->addProduct($product, $objParam);
Add option to quote item
Rewrite Magento ToOrderItem class (add below lines to your di.xml) for adding custom option to order
<preference for="Magento\Quote\Model\Quote\Item\ToOrderItem" type="CustomCompany\CustomModule\Observer\AddOrderDeliveryDate"/>
AddOrderDeliveryDate.php
<?php
namespace CustomCompany\CustomModule\Observer;
use Magento\Framework\DataObject\Copy;
use Magento\Quote\Model\Quote\Item;
use Magento\Quote\Model\Quote\Address\Item as AddressItem;
use Magento\Sales\Api\Data\OrderItemInterfaceFactory as OrderItemFactory;
use Magento\Sales\Api\Data\OrderItemInterface;
class AddOrderDeliveryDate extends \Magento\Quote\Model\Quote\Item\ToOrderItem
{
/**
* #var Copy
*/
protected $objectCopyService;
/**
* #var OrderItemFactory
*/
protected $orderItemFactory;
/**
* #var \Magento\Framework\Api\DataObjectHelper
*/
protected $dataObjectHelper;
/**
* #param OrderItemFactory $orderItemFactory
* #param Copy $objectCopyService
* #param \Magento\Framework\Api\DataObjectHelper $dataObjectHelper
*/
public function __construct(
OrderItemFactory $orderItemFactory,
Copy $objectCopyService,
\Magento\Framework\Api\DataObjectHelper $dataObjectHelper
) {
$this->orderItemFactory = $orderItemFactory;
$this->objectCopyService = $objectCopyService;
$this->dataObjectHelper = $dataObjectHelper;
}
public function convert($item, $data = [])
{
$options = $item->getProductOrderOptions();
if (!$options) {
$options = $item->getProduct()->getTypeInstance()->getOrderOptions($item->getProduct());
}
$orderItemData = $this->objectCopyService->getDataFromFieldset(
'quote_convert_item',
'to_order_item',
$item
);
if (!$item->getNoDiscount()) {
$data = array_merge(
$data,
$this->objectCopyService->getDataFromFieldset(
'quote_convert_item',
'to_order_item_discount',
$item
)
);
}
$orderItem = $this->orderItemFactory->create();
$this->dataObjectHelper->populateWithArray(
$orderItem,
array_merge($orderItemData, $data),
'\Magento\Sales\Api\Data\OrderItemInterface'
);
/**Setting custom options to item **/
if($item->getOptionByCode('additional_options'))
$options['additional_options'] = unserialize($item->getOptionByCode('additional_options')->getValue());
$orderItem->setProductOptions($options);
if ($item->getParentItem()) {
$orderItem->setQtyOrdered(
$orderItemData[OrderItemInterface::QTY_ORDERED] * $item->getParentItem()->getQty()
);
}
return $orderItem;
}
}

Get multiple file data information after upload success codeigniter

When I upload multiple images I would like to be able to display each file name.
I can upload the file fine in to the upload folder, but when I try to get the multiple file_name data it shows error below.
I get this error below
Severity: Warning Message: Illegal string offset 'file_name' Filename:
page/Page_add.php Line Number: 110
Which is here in success part of upload function
$upload_info = $this->upload->data();
foreach ($upload_info as $upload_data) {
echo $upload_data['file_name']; // Line 110
}
Do upload function
public function do_upload() {
$directory = FCPATH . 'uploads/';
if (is_dir($directory)) {
foreach ($_FILES as $field_name => $value) {
if ($value['name'] != '') {
$this->load->library('upload');
$this->upload->initialize($this->do_upload_options());
if (!$this->upload->do_upload($field_name)) {
$this->form_validation->set_message('do_upload', $this->upload->display_errors());
return FALSE;
} else {
$upload_info = $this->upload->data();
foreach ($upload_info as $upload_data) {
echo $upload_data['file_name'];
}
}
}
}
} else {
$this->form_validation->set_message('do_upload', 'Cannot Find Directory' .' '. $directory);
return FALSE;
}
}
public function do_upload_options() {
$config = array();
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|png|jpg';
$config['max_size'] = '30000';
$config['overwrite'] = TRUE;
$config['max_width'] = '0';
$config['max_height'] = '0';
return $config;
}
Each field name has its own name="" example name="fileupload_extra_image0" the number at the end is automatically generated
Vardump
array(2) { ["fileupload_extra_image0"]=> array(14) { ["file_name"]=> string(17) "ci_logo_flame.jpg" ["file_type"]=> string(10) "image/jpeg" ["file_path"]=> string(49) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/" ["full_path"]=> string(66) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/ci_logo_flame.jpg" ["raw_name"]=> string(13) "ci_logo_flame" ["orig_name"]=> string(17) "ci_logo_flame.jpg" ["client_name"]=> string(17) "ci_logo_flame.jpg" ["file_ext"]=> string(4) ".jpg" ["file_size"]=> float(3.61) ["is_image"]=> bool(true) ["image_width"]=> int(100) ["image_height"]=> int(100) ["image_type"]=> string(4) "jpeg" ["image_size_str"]=> string(24) "width="100" height="100"" } ["fileupload_extra_image1"]=> array(14) { ["file_name"]=> string(10) "family.png" ["file_type"]=> string(9) "image/png" ["file_path"]=> string(49) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/" ["full_path"]=> string(59) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/family.png" ["raw_name"]=> string(6) "family" ["orig_name"]=> string(10) "family.png" ["client_name"]=> string(10) "family.png" ["file_ext"]=> string(4) ".png" ["file_size"]=> float(828.1) ["is_image"]=> bool(true) ["image_width"]=> int(670) ["image_height"]=> int(450) ["image_type"]=> string(3) "png" ["image_size_str"]=> string(24) "width="670" height="450"" } }
public function do_upload()
{
$directory = FCPATH . 'uploads/';
$upload_info = [];//array();
if (is_dir($directory)) {
foreach ($_FILES as $field_name => $value) {
if ($value['name'] != '') {
$this->load->library('upload');
$this->upload->initialize($this->do_upload_options());
if (!$this->upload->do_upload($field_name)) {
$this->form_validation->set_message('do_upload', $this->upload->display_errors());
return FALSE;//You would like to make better control here because first one is not file_name would break process
} else {
$upload_info[$field_name] = $this->upload->data();
}
}
}
if ( count($upload_info) > 0 ) {
foreach ($upload_info as $upload_data) {
echo $upload_data['file_name'];
}
}
} else {
$this->form_validation->set_message('do_upload', 'Cannot Find Directory' .' '. $directory);
return FALSE;
}
}
public function do_upload_options()
{
$config = array();
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|png|jpg';
$config['max_size'] = '30000';
$config['overwrite'] = TRUE;
$config['max_width'] = '0';
$config['max_height'] = '0';
return $config;
}

PHP Function to Extract Parts of a Multi-Dimensional Array Based Upon Variable Criteria

Given a multi-dimensional array, I'm looking for a method that will extract various parts of that array, given variable (i.e., different) criteria.
For example, if this is my data:
array(
'0' => array(
'0' => 'aaaaaa',
'1' => 'bbbbb',
'2' => 'ccccc'
),
'1' => array(
'0' => 'aa2ssa',
'1' => 'bb3242bb,
'2' => 'ccccc234'
),
'2' => array(
'0' => 'aaa234aa',
'1' => 'b3242b',
'2' => 'cewrcc'
),
(etc)
)
I want to be able to call a function
function new_array( index, sub_index )
that returns an array based upon the index and sub_index parameters. Using the same data but different parameters would return different data.
Example 1
new_array( array(0, 2), ( array(1, 2), array(0, 2) ) )
Expected results:
array(
'0' => array(
'1' => 'bbbbb',
'2' => 'ccccc'
),
'2' => array(
'0' => 'aaa234aa',
'2' => 'cewrcc'
)
)
Example 2
new_array( array(2), ( array(0, 2) ) )
Expected results:
array(
'2' => array(
'0' =>'aaa234aa',
'1' => 'b3242b'
)
)
Anybody know how to do this? Thank you!
An alternate solution to #Orbling's is this:
function populateData() // CHANGE ME to populate the info how you please
{
$seed = 'abcdefghijklmnopqrstuvwxyz0123456789';
$_ = ''; $length = rand(5,8);
for ($__ = 0; $__ < $length; $__++) $_ .= substr($seed,rand(0,strlen($seed)),1);
return $_;
}
function new_array()
{
$args = func_num_args();
if ($args == 0)
return FALSE; // flag error if no arguments are passed
$template = func_get_arg(0);
if ($template == null || !is_array($template) || $args < (count($template)+1))
return FALSE; // flag error if we don't have enough information
$resultAry = Array();
$arg = 1;
foreach ($template as $t)
{
$resultArySub = Array();
$templateSub = func_get_arg($arg++);
if ($templateSub == FALSE || !is_array($templateSub))
return FALSE; // error checking for valid input
foreach ($templateSub as $tS)
$resultArySub[$tS] = populateData();
$resultAry[$t] = $resultArySub;
}
return $resultAry;
}
header('Content-Type: text/plain');
echo "your request (or so i understood):\r\n";
$test = new_array(array(0,2),array(1,2),array(0,2));
var_dump($test);
echo "\r\nextra array on end is ignored:\r\n";
$test = new_array(array(4,2),array(1,2),array(0,2),array(3,5));
var_dump($test);
echo "\r\nno data is a FALSE:\r\n";
$test = new_array();
var_dump($test);
echo "\r\ntoo few arguments for what was supplied in first argument is a FALSE:\r\n";
$test = new_array(array(1,2,3),array(4,5),array(6,7));
var_dump($test);
echo "\r\nas long as there's as \"array argument\" for every element of the \"first argument\", this will work:\r\n";
$test = new_array(array(1,2,3,4,5,6,7),array(1),array(2),array(3),array(4),array(5),array(6),array(7));
var_dump($test);
echo "\r\nall arguments must be an array\r\n";
$test = new_array(array(1,2),'not','arrays');
var_dump($test);
Results in an array with random entries. The outcome of the above would be:
your request (or so i understood):
array(2) {
[0]=>
array(2) {
[1]=>
string(8) "mjdfsmda"
[2]=>
string(8) "qg2bzsj6"
}
[2]=>
array(2) {
[0]=>
string(7) "345plm8"
[2]=>
string(7) "1exlla6"
}
}
extra array on end is ignored:
array(2) {
[4]=>
array(2) {
[1]=>
string(5) "0ngei"
[2]=>
string(5) "q6tmg"
}
[2]=>
array(2) {
[0]=>
string(7) "4enz61q"
[2]=>
string(6) "6bojtn"
}
}
no data is a FALSE:
bool(false)
too few arguments for what was supplied in first argument is a FALSE:
bool(false)
as long as there's as "array argument" for every element of the "first argument", this will work:
array(7) {
[1]=>
array(1) {
[1]=>
string(7) "ndulmi9"
}
[2]=>
array(1) {
[2]=>
string(7) "jip402j"
}
[3]=>
array(1) {
[3]=>
string(5) "3bn0d"
}
[4]=>
array(1) {
[4]=>
string(8) "b80le1jh"
}
[5]=>
array(1) {
[5]=>
string(5) "x31sw"
}
[6]=>
array(1) {
[6]=>
string(8) "x8e3dge7"
}
[7]=>
array(1) {
[7]=>
string(8) "vcpf997y"
}
}
all arguments must be an array
bool(false)
Assuming that you wish the function to process an existing array and filter out the data, as seems to be the case then you could do this:
function new_array($original, $topKeys, $subKeys) {
if (count($topKeys) != count($subKeys)) {
return $original;
}
$newArray = array();
foreach ($topKeys as $cTopKey) {
$cSubKeys = array_shift($subKeys);
if (array_key_exists($cTopKey, $original)) {
$newArray[$cTopKey] = array();
foreach ($cSubKeys as $cSubKey) {
if (array_key_exists($cSubKey, $original[$cTopKey])) {
$newArray[$cTopKey][$cSubKey] = $original[$cTopKey][$cSubKey];
}
}
}
}
return $newArray;
}
If you have PHP v5.1+ and the indexes are guaranteed to be available, and in order, then I believe you can do it more simply:
function new_array($original, $topKeys, $subKeys) {
$newArray = array_intersect_key($original, array_flip($topKeys));
foreach ($newArray as $cKey => $cSub) {
$cSubKeys = array_shift($subKeys);
$newArray[$cKey] = array_intersect_key($cSub, $cSubKeys);
}
return $newArray;
}
The danger in that is I do not know if array_intersect_key() is defined to keep the original ordering of elements. If not, then further code would need to be added to match the sub keys with the original, ideally the subkeys would be sub arrays of the first parameter anyhow.
why not just
$a = array('0' =>
array('1' => 'bbbb',
'2' => 'ccccc'),
'2' =>
array('0' => 'aaaa',
'2' => 'cewrcc')
);
Why use a function to do the same?

Resources