Explode the string value by using the index value in PHP - php

I have a string that has been concatenated by the rows and columns that has be separated by using the special characters. Below is my code:
$strMaterialDetails = '13-"9"Strawberry%*DEALER%*15%*25%*375%*7.500%*7.500%*28.13%*2.000%*2.000%*6.94#^$14-"9" Yellow white Acrylic Long Pile Ext Roller Set%*DISTRIBUTOR%*45%*75%*3375%*2.500%*2.500%*84.38%*5.000%*5.000%*164.53#^$';
$pairs = explode('#^$', $strMaterialDetails);
foreach ($pairs as $pair) {
list($product, $store, $qty, $unit, $total_price, $discount, $discount_percen, $discount_value, $tax, $tax_percen, $tax_val) = explode('%*', $pair);
echo $store;
}
It works fine I have to insert the values into the database if I print the $store it will print DEALERDISTRIBUTOR
I want to seperate this I don't know how to do. The string here entered is unknown.
Please give any suggestion.

Why not store it in an array?
$stores = array();
foreach ($pairs as $pair) {
list($product,$store,$qty,$unit,$total_price,$discount,$discount_percen,$discount_value,$tax,$tax_percen,$tax_val) = explode('%*', $pair);
$stores[] = $store;
}
print_r($stores); // will contain DEALER at 0th index and DISTRIBUTOR at 1st index
DEMO

Your DEALERDISTRIBUTOR is not store in $store
actualy you are printing the $store in loop without any space that why it is printing combine.
originaly in first loop $store=DEALER then you echo it. and in second loop $store=DISTRIBUTOR so it is confustion only.
you can have Two solution for check it.
Solution : 1
print a new line after echo the $store like this
foreach ($pairs as $pair)
{
list($product,$store,$qty,$unit,$total_price,$discount,$discount_percen,$discount_value,$tax,$tax_percen,$tax_val) = explode('%*#', $pair);
echo $store;
echo "<br/>";
}
Solution : 2 save $store in array
foreach ($pairs as $pair)
{
list($product,$store,$qty,$unit,$total_price,$discount,$discount_percen,$discount_value,$tax,$tax_percen,$tax_val) = explode('%*#', $pair);
$arr_store[] = $store;
}
print_r($arr_store);

Related

“How can to fix the problem ‘ number_format error

I would like to shorten the result. I have used nummber_format but always an error appears.Can someone help me.
$arr = array();
foreach ($order->orderPositions as $tax) {
$arr[] = $tax->tax;
}
$unique_data = array_unique($arr);
foreach ($unique_data as $val) {
$totalTaxes[$val] = $order->orderPositions->where('tax',
$val)->sum('TotalPriceWithTax');
}
/*help is needed here*/ number_format((float)$unique_data,2);
Loop the array and save them as the new format either in a new array or the same
$unique_data = array_unique($arr);
foreach ($unique_data as &$val) { //notice the & if you want to change the data points in the unique array
$totalTaxes[$val] = $order->orderPositions->where('tax', $val)->sum('TotalPriceWithTax');
$val = number_format($val,2); // replaces the data in unique array
$new[] = number_format($val,2); // add to new array if you need unique array
}

how to Increase a counter every foreach complete loop in PHP?

I have a form that registers the values of five machines through a foreach.
followed by checking that the ending has the name of the text field and assigning it to the corresponding variable according to a comparison of patterns:
To save the value correctly I remove the _1 _2 _3 _4 _5 for every key
This is the function
function registerMachines(){
foreach($_POST as $item => $value){
if(preg_match('/_1/', $item)){
$item = explode("_", $item);
$item = $item[0];
$data_1[$item] = $value;
} elseif(preg_match('/_2/', $item)){
$item = explode("_", $item);
$item = $item[0];
$data_2[$item] = $value;
} elseif(preg_match('/_3/', $item)){
$item = explode("_", $item);
$item = $item[0];
$data_3[$item] = $value;
} elseif(preg_match('/_4/', $item)){
$item = explode("_", $item);
$item = $item[0];
$data_4[$item] = $value;
} elseif(preg_match('/_5/', $item)){
$item = explode("_", $item);
$item = $item[0];
$data_5[$item] = $value;
} else {
$configData[$item] = $value;
}
}
}
I want loop every value without assigning a data_number variable for every collection of data.
I get to this function:
$machines = [1, 2, 3, 4, 5];
foreach($_POST as $item => $value){
foreach($machines as $machine) {
$match = '/_'.$machine.'$/';
if(preg_match($match, $item)){
$item = explode("_", $item);
$item = $item[0];
${"machineData_".$machine}[$item] = $value;
} else {
$configData[$item] = $value;
}
}
}
How does it work?
I go through all the values ​​of $ _POST.
I scan internally every machine ($ machine).
I create the pattern to check based on the value of the loop.
If it matches I eliminate the end of the $ item (_1, _2, _3, etc).
I create the variable (array) with the syntax $ {var. $ Machine} and assign it the value.
The problem:
When I go through the 50 input of the machines, the 5 paths are repeated to generate variables, therefore in a var_dump 250 values ​​come out.
What I wish?
I would like to be able to go through each POST value and for this, all the machines will be reviewed and its value assigned to the correct one (array generated with $ {var})
You could use two foreach
foreach ($numbers as $key => $value) {
foreach ($letters as $keylet => $valuelet) {
$data[$value] = $valuelet;
}
}
you should loop every iterate of first array
foreach($numbers as $number){
foreach($letters as $letter){
$data[$number] = $letter;
}
}

PHP get parameters from URL and convert to array

CASE:
I'm trying to get ordered items and quantity from another page, so I'm passing it using GET (http://foo.bar/?view=process-order&itm=1&qty=1000...), then I must to take this parameters and convert to an multidimensional array following this sequence:
EXPECTED:
URL will be: http://foo.bar/?view=foo-bar&itm=1&qty=1000&itm=2&qty=3000&itm=3&qty=1850
[0]=>
[itm]=>'1',
[qty]=>'1000',
[1]=>
[itm]=>'2',
[qty]=>'3000',
[2]=>
[itm]=>'3';
[qty]=>'1850',
etc.
CODE:
$url = $_SERVER['REQUEST_URI']; //get the URL
$items = parse_url($url, PHP_URL_QUERY); //get only the query from URL
$items = explode( '&', $items );//Explode array and remove the &
unset($items[0]); //Remove view request from array
$items = implode(",", $items); //Implode to a string and separate with commas
list($key,$val) = explode(',',$items); //Explode and remove the commas
$items = array($key => $val); //Rebuild array
ACTUAL RESULT:
[itm=1] => [qty=1000]
ACTUAL BEHAVIOUR:
Result leave only the first element in the array and make it like array({[itm=1]=>[qty=1000]}) that anyway isn't what I need.
Even If I've read much pages of PHP docs can't find the solution.
Thanks to all who can help
Your statement list($key,$val) = explode(',',$items); will only fetch the first two items in an array.
Here's a rewritten version
$chunks = explode('&', $_SERVER['QUERY_STRING']);
$items = array();
$current = -1; // so that entries start at 0
foreach ($chunks as $chunk) {
$parts = explode('=', $chunk);
if ($parts[0] == 'itm') {
$current++;
$items[$current]['itm'] = urldecode($parts[1]);
}
elseif ($parts[0] == 'qty') {
$items[$current]['qty'] = urldecode($parts[1]);
}
}
print_r($items);
Here is another version. I only modified the bottom part of your code (first 4 lines are untouched).
$url = $_SERVER['REQUEST_URI']; //get the URL
$items = parse_url($url, PHP_URL_QUERY); //get only the query from URL
$items = explode('&', $items );//Explode array and remove the &
unset($items[0]); //Remove view request from array
$list = array(); // create blank array for storing data
foreach ($items as $item){
list($key, $val) = explode('=', $item);
if ($key === 'itm')
$list[] = ['itm' => $val];
else // qty
$list[count($list) - 1]['qty'] = $val;
}
Hope this helps.

PHP Can't get the right format for array

I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}

How to create multidimensional PHP array from this string?

I have a string I would like to separate and make a multidimensional array out of. The string looks like this:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
Unfortunately, I have no control over how the string is put together, which is why I'm trying to make this array.
My goal is to make an array like this:
$item[1]['color'] // = blue
$item[2]['material'] // = silk
So, here's what I've done:
$item = array();
$i=0; // I know this is messy
$eachitem = explode("item-",$string);
array_shift($eachitem); // get rid of the first empty item
foreach ($eachitem as $values) {
$i++; // Again, very messy
$eachvalue = explode(",",$values);
array_pop($eachvalue); // get rid of the last comma before each new item
foreach ($eachvalue as $key => $value) {
$item[$i][$key] = $value;
}
}
I'm obviously lost with this... any suggestions?
You're mostly there. Just replace your inner foreach with
foreach ($eachvalue as $value) {
$properties = explode(':', $value);
$item[$i][$properties[0]] = $properties[1];
}
You're close, this is how I would do it:
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$substr = explode("item-", $string);
$items = array();
foreach ($substr as $string) {
$subitems = array();
$pairs = explode(",", $string);
foreach ($pairs as $pair) {
list($key, $value) = explode(":", $pair, 2);
$subitems[$key] = $value;
}
$items[] = $subitems;
}
var_dump($items);
Using list here is great :) Do note that you would need the extra count limiter in explode else you might lose data if there are more :.
$array = array();
$string = explode(',', $string);
foreach($string as $part):
$part = trim($part);
if(strlen($part) < 3) continue;
$part = explode(':', $part);
$array[$part[0]] = $part[1];
endforeach;
$string = "item-size:large,color:blue,material:cotton,item-size:medium,color:red,material:silk,";
$num_attr = 3;
$item = array();
$i=$x=0;
foreach(explode(',', trim($string,',')) as $attr)
{
list($key, $value) = explode(':', $attr);
$item[$x+=($i%$num_attr==0?1:0)][$key] = $value;
$i++;
}
Set the $num_attr to the number of item attributes in the string (this will allow adjustments in the future if they grow/shrink). The trim inside the foreach is removing ay "empty" data like the last comma (it will also remove a empty first comma if one ever shows up). The crazy looking $item[$x+=($i%$num_attr==0?1:0)] is taking the modulus of the counter / number of attributes which when it is 0 that means we are on a new product line so we add 1 to x which populates the item number index, if the modulus returns a number then we know we are on the same product so we add 0 which doesn't change the items index so that attribute is added on to the same item.

Categories