How to prepare array in php? - php

$country = explode(",",$post_array['allcountry']);
foreach ($country as $count) {
$array_set = explode("=",$count);
pr($array_set);
}
die;
O:P-
Array
(
[0] => 5
[1] => 100
)
Array
(
[0] => 11
[1] => 150
)
Array
(
[0] => 13
[1] => 200
)
But I need this array to Array
(
[5] => 100,[11] => 150, [13] => 200
)`
How is it possible ?

You need to make first value of exploded array as key and second as its value.
Following is the modified code:
$country = explode(",",$post_array['allcountry']);
$formattedArr = array();
foreach ($country as $count) {
$array_set = explode("=",$count);
$formattedArr[$array_set[0]] = $array_set[1];
}
print_r($formattedArr);

you can change your code to be:
$country = explode(",",$post_array['allcountry']);
$new_arr = array();
foreach ($country as $count) {
$array_set = explode("=",$count);
$new_arr[$count[0]] = $count[1] ;
}
print_r($new_arr);
die;

Here's a simple way to do it:
$input = '5=100,11=150,13=200';
$output = parse_ini_string( str_replace( ',', "\n", $input ) );
Output:
Array
(
[5] => 100
[11] => 150
[13] => 200
)

If you have an array like this:
O:P- Array ( [0] => 5 [1] => 100 ) Array ( [0] => 11 [1] => 150 ) Array ( [0] => 13 [1] => 200 ) ---->>$yourArray
and you need it to be like this:
But I need this array to Array ( [5] => 100,[11] => 150, [13] => 200 ) How is it possible ?
$finalArray = array();
foreach($yourArray as $inside){
$finalArray[$inside[0]]= $inside[1];
}

Related

manipulating multidimensional array

I have a multi-dimensional array. Since the value of the string "volvo" is present twice, I want to combine those keys. Here's the source array:
Array
(
[0] => Array
(
[0] => Volvo
[1] => 22
)
[1] => Array
(
[0] => BMW
[1] => 15
)
[2] => Array
(
[0] => Saab
[1] => 5
)
[3] => Array
(
[0] => Volvo
[1] => 17
)
)
and I'd like to convert it to this one:
Array
(
[0] => Array
(
[0] => Volvo
[1] => 39
)
[1] => Array
(
[0] => BMW
[1] => 15
)
[2] => Array
(
[0] => Saab
[1] => 5
)
)
I think this would make more sense to return an associated array, that way you can do $arr["volvo"], if you're fine with an associated array, just remove the second foreach loop.
If not, this will get the correct output:
<?php
$arr = Array (
Array (
"Volvo",
22
),
Array (
"BMW",
15
),
Array (
"Saab",
5
),
Array (
"Volvo",
17
)
);
$tmpNewArr = Array();
foreach ($arr as $ele) {
if (!isset($arr[$ele[0]])) {
$tmpNewArr[$ele[0]] = 0;
}
$tmpNewArr[$ele[0]] += $ele[1];
}
$newArr = [];
foreach ($tmpNewArr as $key => $ele) {
array_push($newArr,[$key,$ele]);
}
var_dump($newArr);
?>
Here's an eval.in:
https://eval.in/766340
$keyValueCars = [];
foreach($cars as $car){
$brand = $car[0];
$total = $car[1];
if(!isset($keyValueCars[$brand])){
$keyValueCars[$brand] = total;
}
else{
$keyValueCars[$brand] += total;
}
}
You could use
array_unique(Your_array, SORT_REGULAR);

How to parse this simple text-block into a multi-dimensional array, in PHP?

I have a simple text-block; and, its content is:
txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).
And, there is already an simple array, in PHP code:
$my_array = array();
Now, I want to parse into this PHP array, like:
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
All data is general. Could you help me to do it, with PHP?
<?php
// Initially put your input into a variable
$txt=<<<__EOT__
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
__EOT__;
$result = array();
// separate out each row
$rows = explode("\n", $txt);
// loop through each row
foreach($rows as $row) {
// Use a regular expression to find the key and values
$success = preg_match('/^([^(]+)\(([^)]+)\)\.$/', $row, $parts);
// Check the regexp worked
if(!$success) {
echo 'Failed to match row: ' . $row . "\n";
continue;
}
// get the array key from the regexp results
$key = $parts[1];
// the values are all a string, split on the comma to make an array
$values = explode(',', $parts[2]);
// store $key and $values in the result
$result[$key] = $values;
}
// See if it worked
var_dump($result);
Suppose this answer will help you
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_3(val_a,val_b,val_c).
";
$myArry = explode(".", $text);
$resArry = array();
foreach ($myArry as $key => $value) {
if(trim($value)!=""){
$plain = str_replace(array("(",")"),",",$value);
$subArry = explode(",",$plain);
$keyN = explode("(",trim($value));
unset($subArry[array_search($keyN[0],$subArry)]);
unset($subArry[array_search("",$subArry)]);
$resArry[$keyN[0]][]=$subArry;
}
}
echo "<pre/>";
print_r($resArry);
die;
//Output will be like
Array
(
[txt_1] => Array
(
[0] => Array
(
[1] => val_1
[2] => val_2
[3] => val_3
)
)
[txt_2] => Array
(
[0] => Array
(
[1] => val_4
[2] => val_5
[3] => val_6
)
)
[txt_3] => Array
(
[0] => Array
(
[1] => val_a
[2] => val_b
[3] => val_c
)
)
)
$input = 'txt_1(val_1,val_2,val_3).
txt_1(val_4,val_5,val_6).
txt_2(val_7,val_8,val_9).
txt_3(val_10,val_11,val_12).
txt_3(val_13,val_14,val_15).
txt_4(val_16,val_17,val_18).'; // the input string
$temp = explode('.', $input); // seprates from .
$temp = array_filter($temp); // for cutting blank values
$temp = array_map('trim', $temp); // removes newlines
$final = [];
foreach($temp as $val)
{
$key = strtok($val, '('); // search upto token (
$final[$key][] = explode(',' ,strtok(')')); // advance token to )
}
unset($val, $temp); // unset non required things
Here is the output for $final,
Array
(
[txt_1] => Array
(
[0] => Array
(
[0] => val_1
[1] => val_2
[2] => val_3
)
[1] => Array
(
[0] => val_4
[1] => val_5
[2] => val_6
)
)
[txt_2] => Array
(
[0] => Array
(
[0] => val_7
[1] => val_8
[2] => val_9
)
)
[txt_3] => Array
(
[0] => Array
(
[0] => val_10
[1] => val_11
[2] => val_12
)
[1] => Array
(
[0] => val_13
[1] => val_14
[2] => val_15
)
)
[txt_4] => Array
(
[0] => Array
(
[0] => val_16
[1] => val_17
[2] => val_18
)
)
)
Test it here: http://phptester.net/
NOTE: In order to use the short array syntax [] use PHP 5.4
<?php
$text = "
txt_1(val_1,val_2,val_3).
txt_2(val_4,val_5,val_6).
txt_n(val_a,val_b,val_c).
";
$myArray = [];
//You're gonna see why we want to remove this character
//later, it will help us have a cleaner code.
$text = str_replace(')', '', $text);
$arrayGroup = explode('.', $text);
//print_r($arrayGroup);
foreach($arrayGroup as $array) {
$exp = explode('(', $array);
$arrayName = trim($exp[0]);
$arrayValues = explode(',', $exp[1]);
foreach($arrayValues as $value) {
${$arrayName}[] = $value;
}
$myArray[$arrayName] = $$arrayName;
}
echo '<pre>';
print_r($myArray);
echo '</pre>';
echo '<pre>';
print_r($myArray['txt_2']);
echo '</pre>';
After all this, you can use the txt_1 or txt_2 or whatever later, because the variables were created dynamically.
Later in the code you can use $myVar = txt_1[3]; with no problem

Group and merge array row data based on one column

I have an array a bit like:
Array (
[1] => Array
(
[1] => 21
[2] => 3
[0] => Analyst
)
[2] => Array
(
[1] => 47
[2] => 8
[0] => Catalysis
)
[3] => Array
(
[1] => 1
[2] => 0
[0] => Biomaterials
)
[4] => Array
(
[3] => 12
[4] => 2
[0] => Analyst
)
[5] => Array
(
[5] => 12
[6] => 2
[0] => Analyst
)
...
However I would like to renumber those entries with the same [0] value so that I end up with
[1] => Array
(
[1] => 21
[2] => 3
[3] => 12
[4] => 2
[5] => 12
[6] => 2
[0] => Analyst
)
So far I've tried getting the [0] values out of the $results array by putting them in their own array and saying if you're already there then add [3] and [4] to where [1] and [2] are in a new array but it's not working.
$final = array();
$jArray = array();
foreach($results as $key => $result) {
if(!in_array($result[0],$jArray) && !empty($result[0])) {
$jArray[$i] = $result[0];
$i++;
}
}
for($x = 0; $x < count($results); $x++) {
$k = array_search($results[$x][0],$jArray);
if(!isset($results[$x][1]))
$final[$k][1] = $results[$x][1];
if(!isset($results[$x][2]))
$final[$k][2] = $results[$x][2];
if(!isset($results[$x][3]))
$final[$k][3] = $results[$x][3];
if(!isset($results[$x][4]))
$final[$k][4] = $results[$x][4];
if(!isset($results[$x][5]))
$final[$k][5] = $results[$x][5];
if(!isset($results[$x][6]))
$final[$k][6] = $results[$x][6];
}
Any simpler ways of doing this?
You can do this way...
$new_arr=array();
$arkeys = array_unique(array_map(function ($v){ return $v[0];},$arr));
foreach($arr as $k=>$arr1)
{
$new_arr[$arr1[0]][]=array_slice($arr1,0,count($arr1)-1);
}
foreach($arkeys as $v)
{
$new_arr[$v] = call_user_func_array('array_merge', $new_arr[$v]);
}
print_r($new_arr);
OUTPUT :
Array
(
[Analyst] => Array
(
[0] => 21
[1] => 3
[2] => 12
[3] => 2
[4] => 12
[5] => 2
)
[Catalysis] => Array
(
[0] => 47
[1] => 8
)
[Biomaterials] => Array
(
[0] => 1
[1] => 0
)
)
Working Demo
If you just want to group by the first element of the sub array, a single loop is enough:
$result = array();
foreach ($array as $sub_arr) {
$key = $sub_arr[0];
unset($sub_arr[0]);
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] += $sub_arr;
}
Here
$final = array();
foreach($results as $key => $result) {
if (!in_array($result[0], array_keys( $final ) ) && !empty($result[0])) {
$final[$result[0]] = array( $result[0] );
}
foreach($result as $k => $v) {
if ($k != 0 && isset($v)) {
$final[$result[0]][$k] = $v;
}
}
}

rearrange an mutidimention array PHP

I have an array $session that I extract from an awstats file:
# Session range - Number of visits
BEGIN_SESSION 7
1h+ 10
5mn-15mn 9
0s-30s 107
2mn-5mn 7
30s-2mn 21
15mn-30mn 4
30mn-1h 11
END_SESSION
First I wanted to rearrange this by adding the two values of 0s-30s & 30s-2mn and creating another one, here's how I tried it:
$newline="\n";
$lines = explode($newline,$session);
$results = array();
foreach($lines as $line) {
$parts = explode(" ",trim($line),2);
if( count($parts) < 2) continue;
else {
$results[$parts[0]] = intval($parts[1]);
}
}
$temp['0s-30s'] = (isset($results['0s-30s'])?$results['0s-30s']:NULL);
$temp['30s-2mn'] = (isset($results['30s-2mn'])?$results['30s-2mn']:NULL);
$results['0s-2mn'] = $temp['0s-30s'] + $temp['30s-2mn'];
unset($results['0s-30s'],$results['30s-2mn']);
$session = $results['BEGIN_SESSION'].$newline;
foreach($results as $k=>$v) $session .= $k." ".$v.$newline;
$session .= "END_SESSION";
$session = explode("\n", $session) ;
unset($session[(count($session)-1)]) ;
unset($session[0]) ;
unset($session[1]) ;
$sessions = array();
foreach ($session as $key => $value) {
$session[$key] = explode(" ", $value) ;
$sessions[] = array($session[$key][0],trim($session[$key][1])) ;
}
and it displays me this array :
Array
(
[0] => Array
(
[0] => 1h+
[1] => 10
)
[1] => Array
(
[0] => 5mn-15mn
[1] => 9
)
[2] => Array
(
[0] => 2mn-5mn
[1] => 7
)
[3] => Array
(
[0] => 15mn-30mn
[1] => 4
)
[4] => Array
(
[0] => 30mn-1h
[1] => 11
)
[5] => Array
(
[0] => 0s-2mn
[1] => 128
)
)
Is there a way to rearrange my array like this:
Array
(
[0] => Array
(
[0] => 1h+
[1] => 10
)
[1] => Array
(
[0] => 30mn-1h
[1] => 11
)
[2] => Array
(
[0] => 15mn-30mn
[1] => 4
)
[3] => Array
(
[0] => 5mn-15mn
[1] => 9
)
[4] => Array
(
[0] => 2mn-5mn
[1] => 7
)
[5] => Array
(
[0] => 0s-2mn
[1] => 128
)
)
Knowing that $session sometimes come with missing sessions. Any help with this? Thanks.
<?php
$session = 'BEGIN_SESSION 7
1h+ 10
5mn-15mn 9
0s-30s 107
2mn-5mn 7
30s-2mn 21
15mn-30mn 4
30mn-1h 11
END_SESSION';
$newline="\n";
$lines = explode($newline,$session);
$results = array();
foreach($lines as $line) {
$parts = explode(" ", trim($line), 2);
if (in_array($parts[0], array('BEGIN_SESSION', 'END_SESSION'))) continue;
else $results[$parts[0]] = intval($parts[1]);
}
$temp['0s-30s'] = isset($results['0s-30s']) ? $results['0s-30s'] : 0;
$temp['30s-2mn'] = isset($results['30s-2mn']) ? $results['30s-2mn'] : 0;
$results['0s-2mn'] = $temp['0s-30s'] + $temp['30s-2mn'];
unset($results['0s-30s'], $results['30s-2mn']);
$order = array('0s-2mn', '2mn-5mn', '5mn-15mn', '15mn-30mn', '30mn-1h', '1h+');
uksort($results, function($a, $b) use ($order) {
return array_search($a, $order) < array_search($b, $order);
});
var_dump($results);

Array values update

I have an array like this..
Array
(
[0] => Array
(
[0] => 1``
[1] => 2``
[2] => 3``
)
[1] => Array
(
[0] => 4``
[1] => 5``
[2] => 6``
)
[2] => Array
(
[0] =>
[1] => 7``
[2] =>
)
)
I want the result like this below,
$remaining_value = Array
(
[0] => 1`` 4``,
[1] => 2`` 5`` 7``,
[2] => 3`` 6``,
)
How to do this in an single loop.. Plz help me..
If the lower-level arrays will always have the same number of elements then you can do something like this:
$subArrayCount = count( $inputArray );
$outputArray = array();
$firstSubArray = reset( $inputArray );
foreach( $firstSubArray as $key => $value )
{
$outputArray[$key] = $value;
for( $innerLoop = 1; $innerLoop < $subArrayCount; $innerLoop++ )
{
$outputArray[$key].= $inputArray[$innerLoop][$key];
}
}
var_dump( $outputArray );
This should work:
<?php
$remaining_value=array();
foreach($array as $loopv1){
foreach($loopv1 as $key2 => $loopv2){
if(empty($remaining_value[$key2]))$remaining_value[$key2]=$loopv2; else $remaining_value[$key2].=" ".$loopv2;
}
}
?>

Categories