I'm trying to make an associative array from my string, but nothing works and I don't know where the problem is.
My string looks like:
$string = "somethink;452;otherthink;4554;somethinkelse;4514"
I would like to make an associative array, where "text" is the key, and the number is value.
Somethink => 452 otherthink => 4554 Somethinkelse => 4514
I tried to convert the string into an array and then to the associative array but it's not working. I decided to use:
$array=explode(";",$string);
Then tried to use a foreach loop but it's not working. Can somebody help?
Using regex and array_combine:
$string = "somethink;452;otherthink;4554;somethinkelse;4514";
preg_match_all("'([A-Za-z]+);(\d+)'", $string, $matches);
$assoc = array_combine($matches[1], $matches[2]);
print_r($assoc);
Using a traditional for loop:
$string = "somethink;452;otherthink;4554;somethinkelse;4514";
$arr = explode(";", $string);
for ($i = 0; $i < count($arr); $i += 2) {
$assoc[$arr[$i]] = $arr[$i+1];
}
print_r($assoc);
Result:
Array
(
[somethink] => 452
[otherthink] => 4554
[somethinkelse] => 4514
)
Note that there must be an even number of pairs; you can add a condition to test this and use a substitute value for any missing keys, or omit them.
I have an array with some of same ID value as shown in below.
[
{"ID":"126871","total":"200.00","currency":"USD","name":"John"},
{"ID":"126872","total":"2000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"1000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"500.00","currency":"USD","name":"John"},
{"ID":"126872","total":"1000.00","currency":"Euro","name":"John"},
]
If the ID value is duplicate, sum the total value of the same currency. For the different currency of same ID, no need to sum total.
Here is what I want.
[
{"ID":"126871","total":"200.00","currency":"USD","name":"John"},
{"ID":"126872","total":"4000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"500.00","currency":"USD","name":"John"}
]
I am stuck with the above problem. I already tried as much as I can. But I got the wrong result. I'm very appreciative for any advice.
#Cloud I have made function for your requirement and Thanks #M. I. for look into this sum section.
$array = array(
array("ID" => "126871","total"=>"200.00","currency"=>"USD","name"=>"John"),
array("ID" => "126872","total"=>"2000.00","currency"=>"Euro","name"=>"John"),
array("ID" => "126872","total"=>"1000.00","currency"=>"Euro","name"=>"John"),
array("ID" => "126872","total"=>"500.00","currency"=>"USD","name"=>"John"),
array("ID" => "126872","total"=>"1000.00","currency"=>"Euro","name"=>"John"),
);
echo "<pre>";
print_r($array);
function unique_multidim_array($array, $key,$key1,$addedKey) {
$temp_array = array();
$i = 0;
$key_array = array();
$key1_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array) && !in_array($val[$key1], $key1_array)) {
$key_array[$i] = $val[$key];
$key1_array[$i] = $val[$key1];
$temp_array[$i] = $val;
}else{
$pkey = array_search($val[$key],$key_array);
$pkey1 = array_search($val[$key1],$key1_array);
if($pkey==$pkey1){
$temp_array[$pkey][$addedKey] += $val[$addedKey];
}else{
$key_array[$i] = $val[$key];
$key1_array[$i] = $val[$key1];
$temp_array[$i] = $val;
}
// die;
}
$i++;
}
return $temp_array;
}
$nArray = unique_multidim_array($array,"ID","currency","total");
// die;
print_r($nArray);
die;
You will need to:
Convert your json string to a php array with json_decode.
Loop through the rows and group them using compound temporary keys. In other words generate a single string from each row's ID & currency values and use that string as the temporary unique key.
Sum the grouped row's total values.
Then prepare the output array for its return to json by reindexing the rows and calling json_encode().
Code: (Demo)
$json='[
{"ID":"126871","total":"200.00","currency":"USD","name":"John"},
{"ID":"126872","total":"2000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"1000.00","currency":"Euro","name":"John"},
{"ID":"126872","total":"500.00","currency":"USD","name":"John"},
{"ID":"126872","total":"1000.00","currency":"Euro","name":"John"}
]';
$array=json_decode($json,true); // convert to array
foreach($array as $row){
if(!isset($result[$row['ID'].$row['currency']])){
$result[$row['ID'].$row['currency']]=$row; // on first occurrence, store the full row
}else{
$result[$row['ID'].$row['currency']]['total']+=$row['total']; // after first occurrence, add current total to stored total
}
}
$result=json_encode(array_values($result)); // reindex the array and convert to json
echo $result; // display
Output:
[
{"ID":"126871","total":"200.00","currency":"USD","name":"John"},
{"ID":"126872","total":4000,"currency":"Euro","name":"John"},
{"ID":"126872","total":"500.00","currency":"USD","name":"John"}
]
What: Create an array that is grouped by 'ID' and 'Currency'. Accumulate currency for duplicates.
How:
Add rows one at a time to an output array.
If group is not in the array then add it
If it is in the array then add the currency to the existing record.
Demonstration at eval.in
Code:
/** ----------------------------------------------
* Create an output array one row at a time.
*
* Group by Id and currency.
*
* #param array $groups
*
* #return array
*/
function getCurrencyGroups(array $groups)
{
$currencyGroups = array();
foreach ($groups as $item) {
$id = $item['ID'];
$currency = $item['currency'];
$amount = $item['total'];
if (!isset($currencyGroups[$id][$currency])) {
$currencyGroups[$id][$currency] = $amount;
}
else {
$currencyGroups[$id][$currency] += $amount;
}
}
return $currencyGroups;
}
Run it:
$currencyGroups = getCurrencyGroups($source);
Output:
array (size=2)
126871 =>
array (size=1)
'USD' => string '200.00' (length=6)
126872 =>
array (size=2)
'Euro' => float 4000
'USD' => string '500.00' (length=6)
I found myself in a similar situation except for I painted myself into a corner and needed to use the same array for input and output. I also found Manish response to be a little heavy-handed.
foreach($open_po_report as $pkey => &$po_line){
foreach($open_po_report as $dkey => $dupe_item){
//do not compare the exact same line
if($dupe_item['PoNo'].$dupe_item['Line'] === $po_line['PoNo'].$po_line['Line']){
continue;
}
//once you find a duplicate sum the qty to the original occurance
if($dupe_item['ItemVendorItem'] === $po_line['ItemVendorItem']){
$po_line['MyOrder']+=$dupe_item['MyOrder'];
unset($open_po_report[$dkey]);
}
//delete the duplicate entry
}
}
#Cloud Try this.
$array = array(array("ID" => "126871","total"=>"200.00","currency"=>"USD","name"=>"John",),array("ID" => "126871","total"=>"200.00","currency"=>"USD","name"=>"John",),array("ID" => "126872","total"=>"1000.00","currency"=>"Euro","name"=>"John",));
echo "<pre>";
print_r($array);
$unique = array_map('unserialize', array_unique(array_map('serialize', $array)));
Sure #Magnus Eriksson. I am explaining why we use 'serialize' and 'unserialize' in steps :
Step 1: Convert the multidimensional array to one-dimensional array
To convert the multidimensional array to a one-dimensional array, first generate byte stream representation of all the elements (including nested arrays) inside the array. serialize() function can generate byte stream representation of a value. To generate byte stream representation of all the elements, call serialize() function inside array_map() function as a callback function. The result will be a one dimensional array no matter how many levels the multidimensional array has.
Step 2: Make the values unique
To make this one dimensional array unique, use array_unique() function.
Step 3: Revert it to the multidimensional array
Though the array is now unique, the values looks like byte stream representation. To revert it back to the multidimensional array, use unserialize() function.
I hope now why i make this code.
I have an array like:
array{
0 => string 'B.E - ECE',
1 => string 'B.E - EEE',
2 => string 'Msc - Maths',
3 => string 'Msc - Social',
}
So how can I make the array into groups like:
B.E. => ECE, EEE
Msc => Maths,Social
?
I want to do it in PHP. Can anybody help me how to achieve it ?
So is your array split by the "-" character?
so it's Key - Value pairs split by commas?
Ok -
(edit: section removed to clarify answer)
Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:
$array = array {
0 => string 'B.E - ECE' (length=9)
1 => string 'B.E - EEE' (length=9)
2 => string 'Msc - Maths' (length=11)
3 => string 'Msc - Social' (length=12)
}
foreach ($array as $row){
$piece = explode("-",$row);
$key = $piece[0];
$newArray[$key][] = $piece[1];
unset($piece);
}
unset($row) ///tidy up
This will output two arrays each of two arrays:
$newArray[Msc] = array("Maths","Social");
$newArray[B.E] = array("ECE","EEE");
What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.
Printing:
To print the result:
foreach($newArray as $key=>$newRow){
/// there are two rows in this case, [B.E] and [MSc]
print $key.":<br>";
print "<pre>";
///<pre> HTML tag makes output use linebreaks and spaces. neater.
print_r($newRow);
///alternatively use var_dump($newRow);
print "</pre>";
}
Alternatively if you wish to print a known named variable you can write:
print_r($newArray['B.E']);
Which will print all the data in that array. print_r is very useful.
what you want is php's explode. Not sure if this will give you the perfect answer but should give you an idea of what to do next.
$groupedArray = array();
foreach($array as $row){
$split = explode(" - ",$row);
$groupedArray[] = $split[0];
}
array_unique($groupedArray); //This will give you the two groupings
foreach($array as $row){
$split = explode(" - ",$row);
$pos = array_search($split[0],$groupedArray);
if($pos !== FALSE){
$groupedArray[$pos][] = $split[1];
}
}
This should give you a full formatted array called $groupedArray where $array is the array you already have.
Hope this helps!
Hello Everyone I have a Array in php like
array (size=2)
0 => string 'A6,A5,B12,B11,' (length=14)
1 => string 'B6,B5,B8,B7,' (length=12)
on var_dump($arr). How could I convert it to something like
array('A6,A5,B12,B11,B6,B5,B8,B7,')
in php.
here is what i'm doing eaxctly to get the above array
$id= "1";
$data['busInfo']= $this->dashboard_model->find_bus($id);
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$arr =array();
foreach ($data['reservationInfo'] as $reserved){
$seatBooked = $reserved->seats_numbers;
array_push($arr, $seatBooked);
}
var_dump($arr);
I'm using Codeigniter as my framework.
You can just append to a string, then create a single element array with that string (if you actually need an array):
$data['reservationInfo'] = $this->dashboard_model->get_booked_seats_info($id);
$str='';
foreach ($data['reservationInfo'] as $reserved){
$str .= $reserved->seats_numbers;
}
var_dump(array($str));
Or just implode the source array:
var_dump(array(implode('', $this->dashboard_model->get_booked_seats_info($id))));
I'm trying to iterate through an array using for loop. However, the indices of the values of the array I'm working is not properly structured. This means that I can find an element at index number 8, index number 9 there's no element and the next element after 8 is at index number 11. Example:
array (size=4951)
8 => string '9,taobao.com
' (length=14)
11 => string '10,linkedin.com
' (length=17)
12 => string '11,amazon.com
' (length=15)
19 => string '12,live.com
' (length=13)
My question is, how can I make it so that the array doesn't skip indices like this? So that when I try to iterate through the array, it will go through index 8 where it will find 9,taobao.com and then on index 9 it would find 10,linkedin.com. Any suggestion will be greatly appreciated!
Use array_values:
$arr = array_values($arr);
It will rearrenge all keys, starting from 0
Why do not use a foreach loop with key, value (if you need the key)?
foreach($array as $key => $value) {
// Treatment.
}
Use a combination of for and isset :
for ($i = $idx_start, $len = count($array); $i < $len; ++$i) {
if (isset($array[$i])) {
// Do your stuff
}
}
You can re-index the array using the following function.
$reindexed_array = array_values(array_filter($array));
Hope it answers your question.