How to convert string to array? - php

I need to convert string
"name1", "b", "2", "name2", "c", "3", "name3", "b", "2", ....
to an array like
$arr[0]['name'] = "name1";
$arr[0]['char'] = "b";
$arr[0]['qnt'] = "2";
$arr[1]['name'] = "name2";
$arr[1]['char'] = "c";
$arr[1]['qnt'] = "3";
$arr[2]['name'] = "name3";
$arr[2]['char'] = "b";
$arr[2]['qnt'] = "2";
I used explode to extract an string to array but it not work
Any idea?

$input = '"name1", "b", "2", "name2", "c", "3", "name3", "b", "2"';
$input = str_replace('"', '', $input);
$input = explode(', ', $input);
$output = array();
$i = 0;
while ($i < count($input)) {
$output[] = array(
'name' => $input[$i++],
'char' => $input[$i++],
'qnt' => $input[$i++]
);
}
print_r($output);
Output:
Array
(
[0] => Array
(
[name] => name1
[char] => b
[qnt] => 2
)
[1] => Array
(
[name] => name2
[char] => c
[qnt] => 3
)
[2] => Array
(
[name] => name3
[char] => b
[qnt] => 2
)
)

If you do not care about the array keys being numeric, you can do:
$string = 'name1, b, 2, name2, c, 3, name3, b, 2';
print_r( array_chunk( explode(',', $string), 3 ) );

Related

Merge two array and create new

I have problem to create array. I have form.
Form's inputs are tag inputs. First input is option name. When you put any option name the new tag input added in the form.
I post data in controller and create auto variations for product. Eg. Red-S Red-M Blue-S Blue-M ... The Code which i'm using gives variation look like this:
array:4 [
0 => "Red-S"
1 => "Blue-S"
2 => "Red-M"
3 => "Blue-M"
]
And i have another array for option names
array:2 [
0 => "Color"
1 => "Size"
]
I want to create one array look like this:
array:2 [
"Color" => "Red"
"Size" => "S"
]
This is my Controller
function make_combinations($props)
{
if ( empty($props) ) return [];
$keys = array_keys($props);
$key = $keys[0];
$values = $props[$key];
unset($props[$key]);
$rest = make_combinations($props);
if ( empty($values) ) return $rest;
if ( empty($rest) ) return $values;
$combinations = [];
foreach($rest as $comb)
{
foreach($values as $value)
{
$combinations[] = $value . '-' . $comb;
}
}
return $combinations;
}
$inputs = explode(',', $request['option']);
$props = [];
foreach($inputs as $input)
{
$input_key = strtolower($input);
if ( !$request->has($input_key) ) continue;
$input_values = explode(',', $request->input($input_key));
$props[$input_key] = $input_values;
}
$combinations = make_combinations($props);
$result[] = compact('combinations', 'inputs');
return view('system.modules.variants', compact('result'));
}
If I gessed right what are you trying to achieve, having this input:
$inputs = ["Red-S-Cotton", "Blue-Silk-M"];
$keys = ['Color-Size-Material', 'Color-Material-Size'];
By doing a:
$output = array_map(function($key) use ($inputs, $keys) {
$expKeys = explode('-', $keys[$key]);
$expInputs = explode('-', $inputs[$key]);
return array_combine($expKeys, $expInputs);
}, array_keys($inputs));
$output will be:
[
[
"Color" => "Red",
"Size" => "S",
"Material" => "Cotton",
],
[
"Color" => "Blue",
"Material" => "Silk",
"Size" => "M",
]
]
You can skip one loop.
You can write code something like this
$arr = [
0 => "Red-S-Silk-Y",
1 => "Blue-S",
2 => "Red-M-Cotton",
3 => "Blue-M",
];
$arrFinal = [];
$dataArray = [];
foreach($arr AS $value){
$expArr = explode("-",$value);
if(isset($expArr[0])){
$dataArray['color'] = $expArr[0];
}
if(isset($expArr[1])){
$dataArray['size'] = $expArr[1];
}
if(isset($expArr[2])){
$dataArray['Material'] = $expArr[2];
}
if(isset($expArr[3])){
$dataArray['Style'] = $expArr[3];
}
$arrFinal[] = $dataArray;
Unset($dataArray);
}
echo "<pre>";
print_r($arrFinal);
Your output will be something like this.
Array
(
[0] => Array
(
[color] => Red
[size] => S
[Material] => Silk
[Style] => Y
)
[1] => Array
(
[color] => Blue
[size] => S
)
[2] => Array
(
[color] => Red
[size] => M
[Material] => Cotton
)
[3] => Array
(
[color] => Blue
[size] => M
)
)
$result = array_merge($array1, $array2,....);

Sum like values in Multi-Dimensional array php

I need to sum the values in element 1 of my array where the values in element 0 are duplicate.
Here's a small piece of my array
Array
(
[0] => 3
[1] => 1
)
Array
(
[0] => 3
[1] => 2
)
Array
(
[0] => 3
[1] => 128
)
Array
(
[0] => 39
[1] => 4
)
The results i'm expecting to see
Array
(
[0] => 3
[1] => 131
)
Array
(
[0] => 39
[1] => 4
)
I'm still really new to PHP so any help is greatly appreciated.
You can use a combination of array_intersect, array_column and array_sum to only iterate twice. (One for each unique column 0 value).
$col0 = array_column($arr, 0);
$col1 = array_column($arr, 1);
Foreach(array_unique($col0) as $val){
$res[] = [$val, array_sum(array_intersect_key($col1, array_intersect($col0,[$val])))];
}
Var_dump($res);
https://3v4l.org/gKb5b
The way I've done it is made sure all duplicates where put in the same array.
// Your data
$sample = [[3, 1],[3, 2],[3, 128],[39, 4]];
foreach($sample as $array){
$tmp[$array[0]][] = $array[1];
}
# Output: {"3":[1,2,128],"39":[4]}
Now sum the arrays, and put it back to the structure it originally was.
foreach($tmp as $k => $v){
$new[] = [$k, array_sum($v)];
}
# Output: [[3,131],[39,4]]
But many roads lead to Rome.
Try this code. It may help you.
$array = array(["0" => 3, "1" => 1] , ["0" => 3, "1" => 2], ["0" => 3, "1" => 128], ["0" => 39, "1" => 4]);
$finalArray = [];
foreach($array as $a) {
$finalArray[$a[0]][0] = $a[0];
$finalArray[$a[0]][1] = !isset($finalArray[$a[0]][1]) ? $a[1] : $finalArray[$a[0]][1] + $a[1];
}
echo '<pre>';
print_r($finalArray);
exit;
You could do something like this. I have separated into two foreach. Hope it helps.
<?php
$a = [[3,1],[3,2],[3,128],[39,4]];
$result=[];
$temp = [];
foreach($a as $line) {
$temp[$line[0]] += $line[1];
}
foreach($temp as $k => $value) {
$result[]=[$k ,$value];
}
$data =
[
[3,1],
[3,2],
[3,128],
[39,4]
];
foreach($data as $item)
$sums[$item[0]] = ($sums[$item[0]] ?? 0) + $item[1];
$result = array_map(null, array_keys($sums), $sums);
var_export($result);
Output:
array (
0 =>
array (
0 => 3,
1 => 131,
),
1 =>
array (
0 => 39,
1 => 4,
),
)
$arr = [ [ 3, 1],[ 3, 2 ],[ 3, 128], [ 39, 4]];
$sum = [];
foreach($arr as $value) {
$sum[$value[0]][] = $value[1];
}
foreach($sum as $key=>$value ) {
$result[] = [ $key, array_sum($value)];
}
Output:
Array
(
[0] => Array
(
[0] => 3
[1] => 131
)
[1] => Array
(
[0] => 39
[1] => 4
)
)

Indent value from array in php like a table

I've an array like:
$array = array(
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
5 => "F",
6 => "G",
7 => "H",
);
Max lenght $array can be is 9, so max is index = 8 and min is 0 (at least 1 element inside array).
I've to indent this list inside a TCPDF box with limited height where, with some test, i've seen can support max 3 lines. But this box is large so, when the array lenght is bigger than 3, the others element need to be aligned in the side of the first column created like:
A D G
B E H
C F
I can't use X,Y coordinated cause i'm using writeHTML method in TCPDF.
I need to create 3 strings like:
$line1 = "A D G";
$line2 = "B E H";
$line3 = "C F";
What's the best method to create this 3 variables from my array?
UPDATE: using suggest method array_chunk is not the solution for me cause for my purpose I'd like to receive an array like:
Array ( [0] => Array (
[0] => A
[1] => D
[2] => G
)
[1] => Array (
[0] => B
[1] => E
[2] => H
)
[2] => Array (
[0] => C
[1] => F )
)
I think a for loop can solve OP's problem. This is another possible solution that use PHP array functions:
<?php
$array = array(
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
5 => "F",
6 => "G",
7 => "H",
);
$cols = 3;
$array = array_chunk($array, $cols);
$results = array_map(function($index) use ($array) {
return array_column($array, $index);
}, range(0, $cols - 1));
var_dump($results);
View online here: https://eval.in/945787
<?php
$array = array(
0 => "A",
1 => "B",
2 => "C",
3 => "D",
4 => "E",
5 => "F",
6 => "G",
7 => "H",
);
$array_chunk = array_chunk($array, 3,false);
$line = '';
foreach ($array_chunk as $chunk_key => $chunk_value) {
$line = '"';
foreach ($chunk_value as $key => $value) {
$line.=$value." ";
}
$line = "$" . "line" . ($chunk_key+1) . " = " . rtrim($line, " ") . '"' . "<br/>";
echo $line;
$line='';
}
Demo

PHP Get most repeated value in Array

I have an array within an array like this:
Array
(
[0] => Array
(
[name] => B
[id] => 924572
)
[1] => Array
(
[name] => A
[id] => 120689
)
[2] => Array
(
[name] => A
[id] => 120689
)
[3] => Array
(
[name] => C
[id] => 919644
)
[4] => Array
(
[name] => A
[id] => 120689
)
[5] => Array
(
[name] => B
[id] => 924572
)
)
How can I get the most repeated value from object named name and id?
I've already tried the code below but I'm getting an error: Warning: array_count_values(): Can only count STRING and INTEGER values!
$count = array_count_values($info);
arsort($count);
$popular = array_keys($count);
echo $popular[0];
Any fix regarding to this problem?
"Serializing way" for searching most repeated couples (name,id):
$out = array();
foreach($arr as $el){
$key = serialize($el);
if (!isset($out[$key]))
$out[$key]=1;
else
$out[$key]++;
}
arsort($out);
foreach($out as $el=>$count){
$item = unserialize($el);
echo "Name = ".$item['name'].' ID = '.$item['id'].' Count = '.$count.'<br/>';
}
Output:
Name = A ID = 120689 Count = 3
Name = B ID = 924572 Count = 2
Name = C ID = 919644 Count = 1
update Without loop
.....
arsort($out);
$most = unserialize(key($out));
$most_count = array_shift($out);
echo $most['name'];
echo $most['id'];
echo $most_count;
Output:
A
120689
3
A more linear solution.
$arr = Array
(
Array
(
"name" => "B",
"id" => 924572
),
Array
(
"name" => "A",
"id" => 120689
),
Array
(
"name" => "A" ,
"id" => 120689
),
Array
(
"name" => "C",
"id" => 919644
),
Array
(
"name" => "A",
"id" => 120689
),
Array
(
"name" => "B",
"id" => 924572
));
$countArr = Array();
for($i = 0; $i < count($arr); $i++)
{
$tmpArr = $arr[$i];
if(array_key_exists($tmpArr["name"],$countArr))
$countArr[$tmpArr["name"]]++;
else
$countArr[$tmpArr["name"]] = 0;
}
arsort($countArr);
var_dump($countArr);
Maybe you can work with this solution:
<?php
$info = array(
array(
"name" => "B",
"id" => 924572
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "C",
"id" => 919644
),
array(
"name" => "A",
"id" => 120689
),
array(
"name" => "B",
"id" => 924572
),
);
$result = array();
foreach ($info as $infoKey => $infoValue) {
foreach ($infoValue as $itemKey => $itemValue) {
if ($itemKey != "name") {
continue;
}
if (array_key_exists($itemValue, $result)){
$result[$itemValue]++;
continue;
}
$result[$itemValue] = 1;
}
}
arsort($result);
var_dump($result);
Will result in:
array (size=3)
'A' => int 3
'B' => int 2
'C' => int 1
Based on finding the mode and mapping in PHP. Would this work?
$name_array = array_map(function($x) {return $x["name"];}, $info);
$count = array_count_values($name_array);
$mode = array_keys($count, max($count));
To return an array of "name", "id" pairs use:
$return_value = array_filter($info, function($x) use ($mode) { return (in_array($x["name"], $mode));});
Makes use of array_column (requires PHP 5.5 or shim).
$count_values = array_count_values(array_column($array, 'name'));
$most_frequent_name = array_search(max($count_values), $count_values);
Then if you want all arrays with this name:
$items = array_filter($array, function ($v) use ($most_frequent_name) {
return $v['name'] == $most_frequent_name;
});
If several names may have the same top frequency:
$count_values = array_count_values(array_column($array, 'name'));
$most_frequent_names = array_keys($count_values, max($count_values));
$items = array_filter($array, function ($v) use ($most_frequent_names) {
return in_array($v['name'], $most_frequent_names);
});
Try following code. It will give you count of occurrences of all elements
function array_icount_values($arr,$lower=true) {
$arr2=array();
if(!is_array($arr['0'])){$arr=array($arr);}
foreach($arr as $k=> $v){
foreach($v as $v2){
if($lower==true) {$v2=strtolower($v2);}
if(!isset($arr2[$v2])){
$arr2[$v2]=1;
}else{
$arr2[$v2]++;
}
}
}
return $arr2;
}
$arr = array_icount_values($array);
echo "<pre>";
print_r($arr);

Array showing series without duplicate and after last array begins from first in php?

I am using:
$input = array("1", "2", "3", "4", "5");
Now I want to start by printing the first value from the array (1) and another value for the remaining ones (2,3,4,5). Then next time, the print value will be 2 and further values (3,4,5,1). And so on, until the print value is 5 and the other values will be (1,2,3,4).
I am using a for-loop, but after the value 5, the loop should break...
What to do for this case....
out put should be: 1 the first time, then 2 then 3 then 4 then 5 then again 1 then continue on every refresh
Does this do what you are looking for?
<?php
$input = array("1", "2", "3", "4", "5");
$arr = array();
foreach ($input as $item) {
$i = array_shift($input);
$arr[] = $input;
$input[] = $i;
}
print_r($arr);
OUTPUT
Array
(
[0] => Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
)
[1] => Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 1
)
[2] => Array
(
[0] => 4
[1] => 5
[2] => 1
[3] => 2
)
[3] => Array
(
[0] => 5
[1] => 1
[2] => 2
[3] => 3
)
[4] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
)
You want this:
<?php
session_start();
if(!isset($_SESSION['loop_num'])){
$_SESSION['loop_num'] = 1;
}
$loop = true;
echo "Current: {$_SESSION['loop_num']} <br>";
$i = $_SESSION['loop_num'];
while($loop === true) {
if($i >= 5){
$i = 1;
} else {
$i++;
}
if($_SESSION['loop_num'] == $i){
$loop = false;
break;
}
$others[] = $i;
}
if($_SESSION['loop_num'] >= 5){
$_SESSION['loop_num'] = 1;
} else {
$_SESSION['loop_num']++;
}
print_r($others);
?>
Output:
Current: 4
Array ( [0] => 5 [1] => 1 [2] => 2 [3] => 3 )
Current: 5
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
etc..
try implementing this solution:
$size = count($input);
$input = array_merge($input,$input);
for($i=0;$i<$size;$i++){
$output = array_slice($input,$i,$size-1);
print_r($output);
}
If you just want a constantly rotating array that loops forever, this works:
$array = range(1,5);
foreach($array as &$number) {
echo $number . PHP_EOL;
array_push($array, array_shift($array));
}
If you want it to rotate per page load, setting the front number to one variable the rest in line in a dedicated array, this works:
session_start();
if(!$_SESSION['loop_array']) {
$_SESSION['loop_array'] = range(1,5);
}
$current_value = array_shift($_SESSION['loop_array']);
$others_values = $_SESSION['loop_array'];
// Push current value to back of rotation, leaving next in line for
// next page load.
array_push($current_value, $_SESSION['loop_array']);
This will also work with the following arrays (or any array):
$_SESSION['cute'] = array("dog", "cat", "pony", "bunny", "moose");
$_SESSION['ordinals'] = array("first", "second", "third", "fourth", "fifth");
$_SESSION['tick_tock_clock'] = array("I", "II", "III", "IV", "V", "VI",
"VII", "VIII", "IX", "X", "XI", "XII");
$_SESSION['randomness'] = array('butter', 'pillow', 'Alabama', 'bleeding gums');
<?php
$input = array("1", "2", "3", "4", "5");
while(!empty($input)) {
foreach($input as $i) {
var_dump($i);
}
$input = array_splice($input, 0, count($input) - 1);
}
?>

Categories