PHP Convert Array To An Associative Array - php

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

Related

string to associative array conversion

I've been struggling with this for a few days and wanted to throw it out there and see if someone has any ideas.
Basically I have a string e.g
1) "/0/bar"
2) "/build/0/foo/1"
and need to convert this into a multidimensional array
1) $result[0][bar]
2) $result[build][0][foo][1]
So far I've tried:
$query = "/build/0/foo/1";
$queryAr = [];
$current = &$queryAr;
$keys = explode("/", $query);
foreach($keys as $key) {
#$current = &$current[$key];
}
$current = $value;
quieting the output is a pretty hacky way to achive this...
You need to trim the first / of the string. live demo.
<?php
$query = "/build/0/foo/1";
$queryAr = [];
$current = &$queryAr;
$keys = explode("/", trim($query, '/'));
foreach($keys as $key) {
#$current = &$current[$key];
}
$current = $value;
print_r($queryAr);
I tried a recursive function version:
$query = "/build/0/foo/1";
print_r($result = buildNestedArray(explode('/', trim($query, '/'))));
function buildNestedArray($keys)
{
$k = current($keys);
$result = [$k => 'DONE'];
array_shift($keys);
if (sizeof($keys) > 0) { $result[$k] = buildNestedArray($keys); }
return $result;
}
output: Array ( [build] => Array ( [0] => Array ( [foo] => Array ( [1] => DONE ) ) ) )

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

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;
}

PHP - count array based other array (array('a','d')=array('d','a'))

I have array like this:
$array1 = array(Array('a','d'),
Array('c','a'),
Array('d','a'),
Array('a','b','c','d','e'),
);
$array2 = array(array('a','d'), array('a','b','c','d','e')) ;
$result = array();
Here's my code:
foreach ($array2 as $part) {
$key = implode(', ', $part);
if( ! array_key_exists ($key, $array1)) {
$result[$key] = 0;
}
$result[$key] = $result[$key] + 1;
}
foreach ($result as $key => $value) {
echo "$value of {$key}<br/>";
}
I want to count values $array2 based on $array1
I got this one:
1 of a,d
1 of a,b,c,d,e
But I want a result like this:
3 of a,d
1 of a,b,c,d,e
If anybody wonders why there's (3 of a,d), it count from array('a','d'), array('d','a') also counted as array('a','d') and array('a','b','c','d','e')
Try this. Here is a working demo https://eval.in/117810
<?
$array1 = array(array('a','d'),
array('c','a'),
array('d','a'),
array('a','b','c','d','e'),
);
$array2 = array(array('a','d'), array('a','b','c','d','e')) ;
$result = array();
foreach ($array2 as $key=>$part2) {
sort($part2);
if(!isset($result[$key]))$result[$key]=0;
foreach($array1 as $part1) {
$intersect = array_intersect($part1, $part2);
sort($intersect);
if ($intersect === $part2) {
$result[$key]++;
}
}
}
foreach($result as $k=>$v) {
echo $v . " of " . implode(',', $array2[$k]) . "<br/>";
}
?>

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 do i get unique value from an array?

$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
From the above array i need the value Dog alone. how can i get the unique value from an array?. is there any functions in php?...
Thanks
Ravi
Have a look at:
http://php.net/function.array-unique
and maybe:
http://php.net/function.array-count-values
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$counted = array_count_values($a);
$result = array();
foreach($counted as $key => $value) {
if($value === 1) {
$result[] = $key;
}
}
//$result is now an array of only the unique values of $a
print_r($result);
function getArrayItemByValue($search, $array) {
// without any validation and cheking, plain and simple
foreach($array as $key => $value) {
if($search === $value) {
return $key;
}
}
return false;
}
then try using it:
echo $a[getArrayitembyValue('Dog', $a)];
Try with:
$a = array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$aFlip = array_flip($a);
$unique = array();
foreach ( array_count_values( $a ) as $key => $count ) {
if ( $count > 1 ) continue;
// $unique[ array_search($key) ] = $key;
$unique[ $aFlip[$key] ] = $key;
}
Use following function seems to be working & handy.
<?php
$array1 = array('foo', 'bar', 'xyzzy', 'xyzzy', 'xyzzy');
$dup = array_unique(array_diff_assoc($array1, array_unique($array1)));
$result = array_diff($array1, $dup);
print_r($result);
?>
You can see its working here - http://codepad.org/Uu21y6jf
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Cat");
$result = array_unique(a);
print_r($result);
try this one...

Categories