“How can to fix the problem ‘ number_format error - php

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
}

Related

Compare and replace values in array

I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)

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;
}

Sorting data from two different sources (PHP)

I need to combine two different data types, an array and an array object.
I then need to display them on a page in order of a certain attribute (date).
The markup for access is similar to the following:
foreach($array as $item){
$item['date'];
}
and
foreach($object as $item){
$item->post->date
}
is array_merge what I need, or something different?
Not that if possible I'd like to do this on the fly, as data will be changing rapidly and there is no need for storage.
Thanks!
Here's how I would do it:
// array we will use for sorting
$finalArray = array();
// add the array's using the date as the key
foreach($array as $item){
$key = $item['date']; // use date here, example $key = date('l \t\h\e jS',$item['date']);
$finalArray[$key] = $item;
}
// add the objects's using the date as the key
foreach($object as $item){
$finalArray[$item->post->date] = $item;
}
//now sort by keys as Xeoncross noted
ksort($finalArray);
foreach($finalArray as $date=>$objOrArray){
if(is_array($objOrArray)){
//do your array printing here
} else {
//do your object printing here
}
}
Ofcourse we can turn the object into an array with get_object_vars, and use whatever sorting function on the final array, the important part is that we want to sort by date and that's why we need it to be our key.
Hope that helped.
foreach($array as $item){
$array_new[] = $item['date'];
}
foreach($object as $item){
$array_new[] = $item->post->date;
}
sort($array_new);
$dates = array();
foreach ($array as $item) {
  $dates[] = $item['date'];
}
foreach ($object as $item) {
$dates[] = $item->post->date;
}
sort($dates);
foreach ($dates as $date) {
echo $date;
}
You could try this if you need multiple values from the objects (not just date) and you don't mind duplicates being erased.
// $array is already defined right?
$object = json_decode(json_encode($object), TRUE);
$data = array_merge($array, $object);
print_r($data); // now test it
http://us2.php.net/array_merge
http://us3.php.net/json_decode (note the second TRUE param)
Edit
Based on Perfection's answer, (and re-reading the question) I would do this:
$finalArray = array();
foreach($array as $item)
{
$finalArray[$item['date']] = $item;
}
foreach($object as $item)
{
$finalArray[$item->post->date] = json_decode(json_encode($item), TRUE);
}
ksort($finalArray);
foreach($finalArray as $date => $item)
{
// Everything is an array now
}

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.

PHP: Set the value of a multidimensional associative array element using a path defined in a separate array

Ok so I have an array that holds the following elements:
$array['a']['b'][0]['c'];
$array['a']['b'][1]['c'];
$array['a']['d'][0]['c']['c'];
$array['b']['c'];
Then in a separate array, I have defined the path to these values:
$structure[0] = array('a','b','#','c');
$structure[1] = array('a','d','#','c','c');
$structure[2] = array('b','c');
Finally, I have an array holding the values:
$values[0] = array('value0-0','value0-1');
$values[1] = array('value1-0');
$values[2] = array('value2-0');
I'm trying to find a simple function/loop that will be able to apply the values in $values to the array path of $array that is defined in $structure.
The end result would be:
$array['a']['b'][0]['c']='value0-0';
$array['a']['b'][1]['c']='value0-1';
$array['a']['d'][0]['c']['c']='value1-0';
$array['b']['c']='value2-0';
In the case of $values[0] or $values[1], it would be able to loop through each value and substitute the $structure element matching '#' with the iteration number for that particular $value.
Is this simply a case of knuckling down and writing a drawn out recursive function, or is there a smart construct or php function that could provide a more elegant solution?
SOLUTION:
Thanks to Mario, my eventual solution is:
foreach ($struct as $i=>$keys)
foreach ($values[$i] as $val) {
$r = & $array;
foreach ($keys as $key) {
if ($key == "#") { $key = $i; }
$r = & $r[$key]; // move pointer to subarray
}
$r = $val;
}
}
You will have to work with references to traverse the target array:
function inject($array, $struct, $values) {
foreach ($struct as $i=>$keys)
foreach ($values[$i] as $val) {
$r = & $array;
foreach ($keys as $key) {
if ($key == "#") { $key = count($r); }
settype($r[$key], "array");
$r = & $r[$key]; // move pointer to subarray
}
$r = $val;
}

Categories