Convert strings to associative array - php

I have five strings:
$array_key = "f_name, f_qty, f_price, f_cur_date";
$food_name = "Meal for 2, Four Seasons Pizza, Lunch Deal, Pepsi";
$food_qty = "1, 3, 5, 7";
$food_price = "10, 30, 50, 70";
$food_userId = "1, 2, 3, 4";
I need some array like this:
Array (
[0] => Array (
[f_name] => Meal for 2
[f_qty] => 1
[f_price] => 10
[f_cur_date] => 1
)
[1] => Array (
[f_name] => Four Seasons Pizza
[f_qty] => 3
[f_price] => 30
[f_cur_date] => 2
)
[2] => Array (
[f_name] => Lunch Deal
[f_qty] => 5
[f_price] => 50
[f_cur_date] => 3
)
[3] => Array (
[f_name] => Pepsi
[f_qty] => 7
[f_price] => 70
[f_cur_date] => 4
))
I convert strings to array with "explode":
$array_key_parts = explode(",",$array_key);
$food_name_parts = explode(",",$food_name);
$food_qty_parts = explode(",",$food_qty);
$food_price_parts = explode(",",$food_price);
$food_price_parts = explode(",",$food_price);
But don't know how to customize it further.
Basically, I'm getting this strings from query GROUP_CONCAT to use it in fullcalendar.js.

You can make an array using array_map function like below :
$food_name_parts = explode(",",$food_name);
$food_qty_parts = explode(",",$food_qty);
$food_price_parts = explode(",",$food_price);
$array_key_parts = explode(",",$array_key);
$myarray = array_map(function ($f_name, $f_qty, $f_price) {
return compact('f_name','f_qty','f_price');
}, $food_name_parts, $food_qty_parts, $food_price_parts);
echo "<pre>";
print_r($myarray);

Related

How to get data from variable array length?

I have this code:
$ItemID = 'a62442e2-ca1f-4fd1-b80d-0d0dc511758e';
$GET_FreeTextFields = new \Picqer\Financials\Exact\ItemExtraField($connection);
$FreeTextFields = $GET_FreeTextFields->filter("ItemID eq guid'$ItemID'", '', '' );
$FreeTextFields01 = array();
$FreeTextFields02 = array();
foreach($FreeTextFields as $GET_FreeTextFields){
$FreeTextFields01[] = $GET_FreeTextFields->Value;
$FreeTextFields02[] = $GET_FreeTextFields->Number;
}
print_r($FreeTextFields01);
print_r($FreeTextFields02);
This outputs:
Value Array
(
[0] => 390
[1] => 804715
[2] => WW001
[3] => WHT/WHT/WHT
[4] => 39/42
[5] => 804715 WW00139/42
[6] => 3pk Quarter Socks
)
Numbers Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 7
[5] => 8
[6] => 10
)
What this needs to output:
What i want if i use the first output so with 6 values in the array:
$FreeTextField01 = null
$FreeTextField02 = null
$FreeTextField03 = 390
$FreeTextField04 = 804715
$FreeTextField05 = WW001
$FreeTextField06 = WHT/WHT/WHT
$FreeTextField07 = 39/42
$FreeTextField08 = 804715 WW00139/42
$FreeTextField09 = null
$FreeTextField10 = 3pk Quarter Socks
But with other $ItemID, it can also output:
Value Array
(
[0] => 10100153
[1] => 2007
[2] => 350
[3] => 804082
[4] => WW006
[5] => WHT/NNY/OXGM
[6] => 35/38
[7] => 804082 WW00635/38
[8] => 0,00138857
[9] => Champion 3pk Quarter Socks
)
Numbers Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
What i want is that if a variable is not in the numbers list so 1-10, setting it to empty, and if the numbers is in the numbers array setting that number to the corresponding value variable. For example the number at [0] is 1 then set the variable $FreeTextField1 to $NumbersArray[0]->Value.
I keep making all kinds off loops but i just get stuck at the fact that the array length changes so that [6] can be the number 10 at one $itemID, but at another $ItemID, the number can be 6.
I tried researching this but I don't even know what I have to type in google to find this problem, that's why I'm describing it here.
edit i tried describing it a second time:
Yeah I'm having problems describing what i want, so let me try again. I get two arrays as output one with numbers that correspond with place it stands, as example you have FreeTextField0 thru FreeTextField10. What i tried to do is if (Numbers[0] == 0){ $FreeTextField0 = Value[0]}, but then I get the problem that Numbers[0] can be 3 or something else because if FreeTextField1 is empty i don't get a null value but nothing.
What i want if i use the first output so with 6 values in the array:
$FreeTextField01 = null
$FreeTextField02 = null
$FreeTextField03 = 390
$FreeTextField04 = 804715
$FreeTextField05 = WW001
$FreeTextField06 = WHT/WHT/WHT
$FreeTextField07 = 39/42
$FreeTextField08 = 804715 WW00139/42
$FreeTextField09 = null
$FreeTextField10 = 3pk Quarter Socks
I think this is what you're after but I have to say that I think you're barking up the wrong tree here. You really should not dynamically create variables in your script. To me, it is a serious code-smell and I think you should evaluate your design here.
http://sandbox.onlinephpfunctions.com/code/b245a0218ce174e68508139872f394def5409b05
<?php
// Test case
$values = [
'390',
'804715',
'WW001',
'WHT/WHT/WHT',
'39/42',
'804715 WW00139/42',
'3pk Quarter Socks'
];
$numbers = [3, 4, 5, 6, 7, 8, 10];
// Flip the $numbers array and then use the keys to find the corresponding values in the $values array
$intersection = array_unique(array_intersect_key($values, array_flip($numbers)));
// Fill in the missing keys and use `null` as the value
$output = $intersection + array_fill_keys(range(1,10), null);
// Sort the final output by the keys
ksort($output);
// Format the keys to match FreeTextField{00}
$output = array_combine(
array_map(function($k){ return 'FreeTextField'.str_pad($k, 2, '0', STR_PAD_LEFT); }, array_keys($output)),
$output
);
// Use the extract function to bring all those array keys + values into the symbol table.
// You can now use $FreeTextField01 - $FreeTextField10
extract($output);
var_dump($output);
UPDATE
http://sandbox.onlinephpfunctions.com/code/244c4f1ed45db398c48b8330c402b375eb358446
<?php
// Test case
$input = [
['Value' => '390', 'Number' => 3],
['Value' => '804715', 'Number' => 4],
['Value' => 'WW001', 'Number' => 5],
['Value' => 'WHT/WHT/WHT', 'Number' => 6],
['Value' => '39/42', 'Number' => 7],
['Value' => '804715 WW00139/42', 'Number' => 8],
['Value' => '3pk Quarter Socks', 'Number' => 10],
];
$intersection = [];
foreach ($input as $config) {
$value = $config['Value'];
$number = $config['Number'];
$intersection[$number] = $value;
}
// Fill in the missing keys and use `null` as the value
$output = $intersection + array_fill_keys(range(1,10), null);
// Sort the final output by the keys
ksort($output);
// Format the keys to match FreeTextField{00}
$output = array_combine(
array_map(function($k){ return 'FreeTextField'.str_pad($k, 2, '0', STR_PAD_LEFT); }, array_keys($output)),
$output
);
// Use the extract function to bring all those array keys + values into the symbol table.
// You can now use $FreeTextField01 - $FreeTextField10
extract($output);
var_dump($output);
Use ${$var}
If you want to see a doc about this type of var you can see it here:
http://php.net/manual/en/language.variables.variable.php

How to convert array multidimensional array to single array?

my output is
Array ( [bid] => 1 [bookiing_date] => 2014-11-19 )
Array ( [bid] => 2 [bookiing_date] => 2014-11-15 )
Array ( [bid] => 3 [bookiing_date] => 2015-01-10 )
Array ( [bid] => 4 [bookiing_date] => 2015-01-27 )
but i want to convert in this form..
$date = ['2015-01-10','2015-01-27','2014-11-19'];
Please any one help me
What you've written above doesn't look too much like PHP, but something like this should do the trick
$single_dimensional_array = array();
foreach($multi_dimensional_array as $array_item) {
if(isset($array_item['bookiing_date'])) {
$single_dimensional_array[] = $array_item['bookiing_date'];
}
}
echo(var_export($single_dimensional_array), true);
Btw, the $single_dimensional_array[] = syntax above simply pushes the value on the right side of the equal sign onto the end of the array on the left side of the equal sign.
There is a very simple approach to get that... I think you did not tried anyway..here is the basic and simple answer ...
$sing_arr = array();
$multi_arr = array(array ( "bid"=> 1, "bookiing_date"=> "2014-11-19" ) ,
array ( "bid"=> 2, "bookiing_date"=> "2014-11-15" ) ,
array ( "bid"=> 3, "bookiing_date"=> "2015-01-10" ) ,
array ( "bid"=> 4 ,"bookiing_date"=> "2015-01-27" )
);
foreach($multi_arr as $key=>$val)
{
array_push($sing_arr,"'".$val["bookiing_date"]."'");
}
echo var_dump($sing_arr);
You Can Loop Through the array using foreach and store the date in another array:
Code:
<?php
$array1=array(
Array ( "bid" => 1 ,"bookiing_date" => "2014-11-19" ),
Array ( "bid" => 2 ,"bookiing_date" => "2014-11-15" ),
Array ( "bid" => 3 ,"bookiing_date" => "2015-01-10" ),
Array ( "bid" => 4 ,"bookiing_date" => "2015-01-27" )
);
// print_r($array1);
$date=array();
foreach ($array1 as $temparray){
$date[]=$temparray["bookiing_date"];
}
print_r($date);
Output:
Array
(
[0] => 2014-11-19
[1] => 2014-11-15
[2] => 2015-01-10
[3] => 2015-01-27
)
Use this
$array = array(array('bid' => 1, 'bookiing_date' => 2014 - 11 - 19),
array('bid' => 2, 'bookiing_date' => 2014 - 11 - 15),
array('bid' => 3, 'bookiing_date' => 2015 - 01 - 10),
array('bid' => 4, 'bookiing_date' => 2015 - 01 - 27));
$data = array();
foreach ($array as $array_item){
if(isset($array_item['bookiing_date'])) {
$data[] = $array_item['bookiing_date'];
}
}
print_r($data);
if you are using PHP 5.5+, use array_column()
$data = array_column($array, 'bookiing_date');
print_r($data);

Get array element with sub elements without repeating in PHP

I walk around here with some hesitation, I have passed an array with sub elements (so to speak) and I need three random values ​​but these are obtained without repeating.
The array is as follows:
Array
(
[0] => Array
(
[uid] => 1
[ticket_code] => 0oreb8yo
)
[1] => Array
(
[uid] => 1
[ticket_code] => 2oeii8hm
)
[2] => Array
(
[uid] => 1
[ticket_code] => m0dwtjiw
)
[3] => Array
(
[uid] => 1
[ticket_code] => q6c7cymb
)
[4] => Array
(
[uid] => 1
[ticket_code] => zyqhm5bj
)
[5] => Array
(
[uid] => 1
[ticket_code] => amdqzjpi
)
[6] => Array
(
[uid] => 2
[ticket_code] => tzql7l42
)
[7] => Array
(
[uid] => 2
[ticket_code] => gap0r6vf
)
[8] => Array
(
[uid] => 2
[ticket_code] => ypqum5yz
)
[9] => Array
(
[uid] => 4
[ticket_code] => smupluac
)
[10] => Array
(
[uid] => 4
[ticket_code] => 9d8jsha7
)
[11] => Array
(
[uid] => 5
[ticket_code] => 6hdnja42
)
)
And I need you to get 3 "ticket_code" but no right to repeat the "uid".
I've been on trying as follows, but also repeats the "uid".
$ticketsWinners = array();
for ($i=0; $i < 3; $i++) {
$aux = array_rand($allTickets);
$aux2 = $allTickets[$aux]['uid'];
$ticketsWinners[] = array(
'uid' => $aux2,
'ticket_code' => $allTickets[$aux]['ticket_code']
);
}
Any way to do it without repeats?
We thank you in advance if anyone knows of something ^^
Try something like:
$ticketsWinners = array();
while (sizeof($ticketsWinners) < 3) {
$aux = array_rand($allTickets);
// array_rand return array of keys so you need first value only
$uid = $allTickets[$aux[0]]['uid']
// add uid as a key so ass not tot check all $allTickets values
if (!isset($ticketsWinners[$uid]))
$ticketsWinners[$uid] = $allTickets[$aux[0]];
}
// if you need $allTickets back to numeric keys [0, 1, 2]
$allTickets = array_values($allTickets);
if you're afraid of infinite loops (that can take place really) then try this:
$ticketsWinners = array();
// shuffle array before checking
shuffle($allTickets);
foreach ($allTickets as $tick_data) {
$uid = $tick_data['uid'];
if (!isset($ticketsWinners[$uid]))
$ticketsWinners[$uid] = $tick_data;
if (sizeof($ticketsWinners) == 3)
break;
}
Here in worst case you check $allTickets array and get winners of size <= 3.
Try this:
$ticketsWinners = array();
$ticketUid = array();
for ($i=0; $i < 3; $i++) {
$aux = array_rand($allTickets);
$aux2 = $allTickets[$aux]['uid'];
if(! in_array($aux2, $ticketUid)) {
$ticketUid[$i] = $aux2;
$ticketsWinners[] = array(
'uid' => $aux2,
'ticket_code' => $allTickets[$aux]['ticket_code']
);
} else {
$i--;
}
}
this structure would be better ( added benefit of ticket numbers being unique )
$tickets = Array
(
'0oreb8yo' => 1,
'2oeii8hm' => 1,
'm0dwtjiw' => 1,
'q6c7cymb' => 1,
'zyqhm5bj' => 1,
'amdqzjpi' => 1,
'tzql7l42' => 2,
'gap0r6vf' => 2,
'ypqum5yz' => 2,
'smupluac' => 3,
'9d8jsha7' => 4,
'6hdnja42' => 5,
);
$winners = array();
$picks = 3;
for($i = 0; $i < $picks; $i++){
if(count($tickets) == 0 ){
break; //or error -- shouldn't need this unless picks exceed uids
}
$ticket = array_rand($tickets);
$winner = $tickets[$ticket];
$winners[] = $winner;
$tickets = array_filter($tickets, function($item) use ($winner){
return $winner != $item;
});
}
echo '<pre>';
var_export($winners);
outputs
array (
0 => 2,
1 => 1,
2 => 4,
)
array (
0 => 2,
1 => 1,
2 => 3,
)
array (
0 => 1,
1 => 3,
2 => 2,
)
unlike the while option, this will reduce the operations for each loop of the for loop by reducing the ticket array by the uid. It's also the only way to insure your not always pulling out a user with tickets, what if user 1 bought 90% of the tickets, you'd loop on him 90% of the time, in any case you have to reduce the ticket array by winners if they can win only once. In essence you remove each uid from the list when they win. You can also be sure that each ticket has the same chance to win ( as well as array_rand is random that is ) - they all have equal footing.
ticket array reduction
after loop1
array (
'tzql7l42' => 2,
'gap0r6vf' => 2,
'ypqum5yz' => 2,
'smupluac' => 3,
'9d8jsha7' => 4,
'6hdnja42' => 5,
)
after loop2
array (
'smupluac' => 3,
'9d8jsha7' => 4,
'6hdnja42' => 5,
)
after loop3
array (
'smupluac' => 3,
'6hdnja42' => 5,
)
winners
array (
0 => 1,
1 => 2,
2 => 4,
)
to return both the uid and wining ticket change
$winners[] = $winner;
to
$winners[$ticket] = $tickets[$ticket];
now winners will be, just like the input array
ticketnumber => uid
ticket is the key ( which is the ticket ) and winner is the value ( which is the uid )

Splitting one Array into many Array in PHP

I'm in need of splitting of the single array into multiple array for some report generating purpose.
I have an array like this which I have given below.
Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
I want to split the above to,
Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
)
Array
(
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
)
Array
(
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
How can I do this in PHP ??
$oldarray=array('blah_1'=>1,'blahblah_1'=>31,'blahblahblah_1'=>25,
'blah_3'=>1,'blahblah_3'=>3,'blahblahblah_3'=>5,
'blah_10'=>1,'blahblah_10'=>10,'blahblahblah_10'=>2
)
$newarray=array();
foreach ($oldarray as $key=>$val) { //Loops through each element in your original array
$parts=array_reverse(explode('_',$key)); //Splits the key around _ and reverses
$newarray[$parts[0]][$key]=$val; //Gets the first part (the number) and adds the
//value to a new array based on this number.
}
The output will be:
Array (
[1]=>Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
)
[3]=>Array
(
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
)
[10]=>Array
(
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
)
Use array_chunk. Example:
<?php
$chunks = array_chunk($yourarray, 3);
print_r($chunks);
?>
Use array_chunk
i.e
$a = array(1,2,3,4,5,6,7);
var_dump(array_chunk($a, 3));
Not sure if you are looking for array_slice
but take a look at this example:
<?php
$input = array("a", "b", "c", "d", "e");
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
will result in this:
Array
(
[0] => c
[1] => d
)
Array
(
[2] => c
[3] => d
)
array_chunk ( array $input , int $size);

Group and Sum this Array

I have an array that's output is this:
Array ( [winners] =>
Array ( [0] => Gold Member
[1] => CROTCH SNIFFER
[2] => TEAM #1 )
[prizeTotal] => 20 )
Array ( [winners] =>
Array ( [0] => TEAM #1
[1] => CROTCH SNIFFER )
[prizeTotal] => 60 )
Array ( [winners] =>
Array ( [0] => Gold Member
[1] => TEAM #1 )
[prizeTotal] => 30 )
Array ( [winners] =>
Array ( [0] => TEAM #1
[1] => TEAM #2
[2] => SCREW-NUT-BOLT )
[prizeTotal] => 90 )
Please forgive the names...it's not my DB.
I can not change the way the array is show here.
With that being said how can I group and sum?
1. For each winners array there is a prizeTotal below the team names. That prize total should be the value of each teamName above it.
Example
Array ( [winners] =>
Array ( [0] => Gold Member
[1] => CROTCH SNIFFER
[2] => TEAM #1 )
[prizeTotal] => 20 )
Gold Member should have 20
CROTCH SNIFFER should have 20
TEAM #1 should have 20 AND
Array ( [winners] =>
Array ( [0] => TEAM #1
[1] => CROTCH SNIFFER )
[prizeTotal] => 60 )
TEAM #1 should have 60
CROTCH SNIFFER sould have 60....etc....
Then I want to group by team name and sum so that I can display...
CROTCH SNIFFER = 80
Gold Member = 50
TEAM #1 = 200
Team #2 = 90.
Thanks in advance...
Assuming you can collect all your arrays into one i.e. :
$arrays = array($array1,$array2,....,$arrayn);
then
$grouping = array();
foreach($arrays AS $array)
{
foreach($array['winners'] AS $k=>$v)
{
//check if the array key is a number, will contain a team, and if that
//them is not alreay listed
if(is_numeric($k) && !array_key_exists($v,$grouping))
$grouping[$v] = 0;
//sum the prize to the team's sum
$grouping[$v] += intval($array['winners']['prizeTotal']);
}
}
//the following is just for debugging
print_r($grouping);
this should produce something like:
$grouping[TEAM #1] = 200
$grouping[TEAM #2] = 90
$grouping[CROTCH SNIFFER] = 200
...
You need to make a new array to hold your results, then for each of your existing arrays, check if you're already processed one for that team
If you have, then simply add the prizeTotal to the prizeTotal stored in your new array's entry for that team.
If not, simply add the team's entry to your new array.
I have made a function that imitates mysql SUM() and GROUP BY. I hope it will fit your needs:
$in_a = array(
array("a" => 0,"b"=>0,"s"=> 1),
array("a" => 0,"b"=>0,"s"=> 2),
array("a" => 1,"b"=>1,"s"=> 1),
array("a" => 0,"b"=>1,"s"=> 1),
array("a" => 0,"b"=>1,"s"=> 1),
array("a" => 1,"b"=>0,"s"=> 1),
array("a" => 0,"b"=>1,"s"=> 1),
array("a" => 1,"b"=>1,"s"=> 1),
array("a" => 1,"b"=>0,"s"=> 1),
);//input array exaple
$group_by_a = array("a","b");//input array will be grouped by these
$sum_a = array("s"); //'s' values of input will be summed
$out_a = array(); //this is the output array
foreach($in_a as $in_i => $in)
{
$add = false;
foreach($out_a as $out_i => $out)
{
$add = true;
foreach($group_by_a as $group_by)
if($in[$group_by] != $out[$group_by])
{
$add = false;
break;
}
if($add)
{
foreach($sum_a as $sum)
$out_a[$out_i][$sum] += $in[$sum];
break;
}
}
if(!$add)
{
foreach($group_by_a as $group_by)
$out_a[$in_i][$group_by] = $in[$group_by];
foreach($sum_a as $sum)
$out_a[$in_i][$sum] = $in[$sum];
}
}
the result:
Array
(
[0] => Array
(
[a] => 0
[b] => 0
[s] => 3
)
[2] => Array
(
[a] => 1
[b] => 1
[s] => 2
)
[3] => Array
(
[a] => 0
[b] => 1
[s] => 3
)
[5] => Array
(
[a] => 1
[b] => 0
[s] => 2
)
)

Categories