How to change $array[x[y]] to $array[x][y] - php

How to change the array:
$array['db[blabla]']
to this array:
$array['db']['blabla']
Thanks.

Here is my crack at it (tested)
$array['db[blabla]'] = 10;
$newArr = array();
foreach($array as $key => $value) {
$r = explode("[",$key);
$newArr[$r[0]][str_replace(']', '', $r[1])] = $value;
}

Related

PHP Get duplicate values in array and average second value

I have an array that looks like this:
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
I Want to find duplicate values in the first column and avarage its values from the second column.
So that this("1",3),("2",5),("2",2),("5",2),("90",1),("5",6),("2",2)
ends up like this ("1",3),("2",3),("5",4),("90",1)
Try this tested solution
I got the required Output
$ratingsInPosts = array
(
array("1",3),
array("2",5),
array("2",2),
array("5",2),
array("90",1),
array("5",6),
array("2",2),
);
$arr1 = array_column($ratingsInPosts, 0);
$p = array_count_values($arr1);
foreach($p as $key => $value)
{
$sum = 0;
for($i=0; $i < $value; $i++)
{
$pos = array_search($key, $arr1);
$sum += $ratingsInPosts[$pos][1];
unset($arr1[$pos]);
unset($ratingsInPosts[$pos]);
}
$re[] = array('"'.$key.'"',$sum/$value);
}
print_r($re);
I hope it helps you:
$groups = array();
// in this loop we group values by first column
foreach ($ratingsInPosts as $row) {
$key = $row[0];
if (!isset($groups[$key]) {
$groups[$key] = array();
}
$groups[$key][] = $row[1];
}
$result = array();
foreach ($groups as $key => $value) {
$avg = array_sum($value) / count($value);
$row = array($key, $avg);
$result[] = $row;
}
<?php
header('Content-Type: text/plain');
$ratingsInPosts = array(array("1",3),array("2",5),array("2",2),array("5",2),array("90",1),array("5",6),array("2",2));
$result = array();
$output = array();
foreach($ratingsInPosts as $array){
$result[$array[0]][] = $array[1];
}
foreach($result as $key=>$array){
$output[] = array($key,round(array_sum($array)/count($array)));
}
var_export($output);
?>

PHP Convert Array To An Associative Array

How do I convert the array
Array
(
[1] => a,b,c
[2] => x,y,z
)
into an associative array like
Array
(
[a]=> b,c
[x]=> y,z
)
Basically want to convert value of an array into a key.
How about this:
$arr = array('a,b,c','x,y,z');
$newArr = array();
foreach($arr as $key => $value) {
$value = explode(",",$value);
$firstValue = $value[0];
array_shift($value);
$newArr[$firstValue] = implode(",",$value);
}
print_r($newArr); //Array ( [a] => b,c [x] => y,z )
A faster solution:
foreach($array as $item){
$x = explode(',',$item);
$new_array[$x[0]] = implode(','array($x[1],$x[2]));
}
print_r($new_array);
Try out this,
$newArray = array();
foreach($array as $data){
$values = explode(",",$data);
$key = array_shift($values);
$newArray[$key] = implode($values,",");
}
print_r($newArray);
DEMO.
Do this:
$myArray=array(1=>'a,b,c', 2=>x,y,z);
foreach($myArray as $val){
$Xval=explode(",",$val);
$newKey=$Xval[0];
unset($Xval[0]);
$newArray[$newKey]=implode(",",$Xval);
}
Try like
$res = array();
foreach($my_arr as $value)
{
$my_var[] = explode(',',$value);
$i = 0;
foreach($my_var as $ky)
{
if($i++ != 0)
$exp_arr[] = $ky;
}
$res[$my_var[0]] = implode(',',$exp_arr);
}
or you can unset like
foreach($my_arr as $value)
{
$my_var[] = explode(',',$value);
$temp = $my_var[0];
unset($my_var[0]);
$res[$temp] = implode(',',$my_var);
}
try this
<?php
$array=array('a,b,c', 'x,y,z');
foreach($array as $key=>$val)
{
$array[substr($val,0,1)]=substr($val,2);
unset($array[$key]);
}
print_r($array);
?>
See Demo

PHP set dynamic array index

I have the following key/value from my $_POST variable:
Array
(
'translations_0_comment' => 'Greetings from UK'
)
What I would like is to set this values to the following array
$data[translations][0][comment] = 'Greetings from UK';
So the idea is that I can have anything in my KEY values, and from that I will populate an array.
Is there any safe way to do this without using eval() ?
All help is appreciated.
UPDATE:
this would be the idea with eval()
foreach ($_POST as $key => $dataValue) {
$a = explode("_", $key);
$builder = '$object';
foreach ($a as $value) {
$builder.='['.$value.']';
}
$builder.=' = '.$dataValue.';';
eval($builder);
}
I think you are looking for this
function set_value($object, $paths, $value, $index){
$key = $paths[$index];
$sub_object = $object[$key];
if (!is_array($sub_object)){
$object[$key] = $value;
}else{
$index = $index+1;
$object[$key] = set_value($sub_object, $paths, $value, $index);
}
return $object;
}
explode() is what you need:
$data = array();
foreach ($postData as $key => $val) {
$explodedKey = explode('_', $key);
$data[$explodedKey[0]][$explodedKey[1]][explodedKey[2]] = $val;
}
No need to use eval().
I think this is what you are looking for
Example
In your form which generate the $_POST data rename the input attribute as follows
<input name="data[translations][0][comment]" />
and now your $_POST['data'] will be an array
$data = array();
foreach ($_POST as $keys => $val) {
$keys_list = explode('_', $keys);
$link = &$data;
foreach ($keys_list as $key) {
$link[$key] = $val;
$link = &$link[$key];
}
}
Try this one sir.
$array = array
(
'TRY_THIS_ONE_SIR_PLEASE_THANKS' => 'Greetings from UK'
);
$array1 = array_keys($array);
$arrValue = array_values($array);
$array1 = explode("_", $array1[0]);
$ctr = count($array1);
for($i=0; $i<$ctr; $i++)
{
$start .= "array(\"".$array1[$i]."\" => ";
$end .=")";
}
$start = $start ."\"".$arrValue[0]."\"".$end;
eval("\$arr = $start;");
print_r($arr);

How to check for duplicates in an array and then do something with their values in PHP?

I have an array for example ("1:2","5:90","7:12",1:70,"29:60") Wherein ID and Qty are separated by a ':' (colon), what I want to do is when there's a duplicate of IDs the program will add the qty and return the new set of arrays so in the example it will become ("1:72","5:90","7:12","29:60").
Ex.2
("1:2","5:90","7:12","1:70","29:60","1:5")
becomes
("1:77","5:90","7:12","29:60").
<?php
$arr = array("1:2","5:90","7:12", "1:70","29:60");
$newArr = array();
foreach($arr as $key => $value) {
list($id, $quantity) = explode(':', $value);
if(isset($newArr[$id]))
$newArr[$id] += $quantity;
else
$newArr[$id] = $quantity;
}
foreach($newArr as $key => $value) {
$newArr[$key] = "$key:$value";
}
print_r($newArr);
Simple step by step:
$arr = array("1:2","5:90","7:12","1:70","29:60");
$tmp = array();
foreach($arr as $item)
{
list($id, $value) = explode(':', $item);
if (isset($tmp[$id]))
$tmp[$id] += $value;
else
$tmp[$id] = $value;
}
$arr = array();
foreach($tmp as $id => $value)
array_push($arr, $id . ':' . $value);
var_dump($arr);
Assuming the data format is an actual array, or you can parse it into one:
$data = array("1:2","5:90","7:12","1:70","29:60","1:5");
$values = array();
foreach ($data as $value) {
list($id, $qty) = explode(':', $value);
if (isset($values[$id])) {
$values[$id] += $qty;
} else {
$values[$id] = $qty;
}
}
foreach ($values as $id => &$qty) {
$qty = "$id:$qty";
}
$values = array_values($values);
Try to do like this
$array = array("1:2","5:90","7:12","1:70","29:60","1:5");
$result = array();
$sum = array();
foreach($array as $value)
{
list($k,$v) = explode(':',$value);
$sum[$k] += $v;
$result[$k] = $k.':'.$sum[$k];
}
unset($sum);
print_r($result);

How to get values in an array this way with PHP?

From:
$arr = array(array('key1'=>'A',...),array('key1'=>'B',...));
to:
array('A','B',..);
$output = array();
foreach ($arr as $array_piece) {
$output = array_merge($output, $array_piece);
}
return array_values($output);
On the other hand, if you want the first value from each array, what you want is...
$output = array();
foreach ($arr as $array_piece) {
$output[] = array_unshift($array_piece);
}
But I'm thinking you want the first one.
Relatively simple conversion by looping:
$newArray = array()
foreach ($arr as $a) {
foreach ($a as $key => $value) {
$newArray[] = $value;
}
}
Or, perhaps more elegantly:
function flatten($concatenation, $subArray) {
return array_merge($concatenation, array_values($subArray));
}
$newArray = array_reduce($arr, "flatten", array());
John's solution is also nice.
Something like this should work
<?
$arr = array(array('key1'=>'A','key2'=>'B'),array('key1'=>'C','key2'=>'D'));
$new_array = array();
foreach ($arr as $key => $value) {
$new_array = array_merge($new_array, array_values($value));
}
var_export($new_array);
?>
If you want all the values in each array inside your main array.
function collapse($input) {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf = array_merge($buf, collapse($i));
}
else $buf[] = $input;
return $buf;
}
Above is a modified unsplat function, which could also be used:
function unsplat($input, $delim="\t") {
$buf = array();
if(is_array($input)) {
foreach($input as $i) $buf[] = unsplat($i, $delim);
}
else $buf[] = $input;
return implode($delim, $buf);
}
$newarray = explode("\0", unsplat($oldarray, "\0"));

Categories