Convert an array of string to an array of arrays? - php

Sorry if it's obvious for you guys, but here what i'm tryiny to do:
I have the following array :
$myArray=Array ( "024848772" ,"0550244954", "0560084252","0559180203","0673466366","021648334" ....);
And I want to have it like this :
Array ( array("024848772"),array("0550244954"),array("0560084252"),array("0559180203"),array("0673466366"),array("021648334") ....);

<?php
$a=array(1,2,3,4,5);
function fun($v) {
return array($v);
}
print_r(array_map("fun",$a));

Loop over the array and add the result to an accumulator wrapping them in an array:
$acc = array();
foreach($myArray as $someString){
$acc[] = array($someString);
}
var_dump($acc);
Example in sandbox here.

Try this code:
$myArray=Array ( "024848772" ,"0550244954", "0560084252","0559180203","0673466366","021648334" );
$arrays = array();
foreach ($myArray as $x)
$arrays[] = array($x);
//print_r($arrays);

Not really seeing the problem. Your original syntax works.
$myArray = Array ( array("024848772"),array("0550244954"),array("0560084252"),array("0559180203"),array("0673466366"),array("021648334"));
var_dump($myArray);

Related

Put string into key value array

Hi I got the following string:
info:infotext,
dimensions:dimensionstext
and i need to put these values into an array in PHP. What is the regex function to put these into an array. I studied the regex codes but it's kinds confusing to me.
I want to put the info as the key and he infotext as the value into an array like this:
Array {
[info] => infotext
[dimensions] => dimensionstext
}
Demo here
<?php
$string ='info:infotext,
dimensions:dimensionstext';
$array = array_map(function($v){return explode(':', trim($v));}, explode(',', $string));
foreach($array as $v)
{
$o[$v[0]] = $v[1];
}
print_r($o);
You can use array_chunk and array_combine
<?php
$input = 'info:infotext,
dimensions:dimensionstext';
$chunks = array_chunk(preg_split('/(:|,)/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));
print_r($result);
http://ideone.com/dRtref

Unique php multidimensional array and sort by occurrence

I have a PHP multiD array like:-
$a = array($arrayA, $arrayB, $arrayA, $arrayC, $arrayC, $arrayA...........)
how can I get a resulting array which have distinct elements from this array and sorted with the more occurrence first like:-
array( $arrayA, $arrayB, $arrayC)
because array $arrayA was 3 times in first array so it comes first in resulting array.
I have tried :-
$newArray = array();
$count = count($a);
$i = 0;
foreach ($a as $el) {
if (!in_array($el, $newArray)) {
$newArray[$i] = $el;
$i++;
}else{
$oldKey = array_search($el, $newArray);
$newArray[$oldKey+$count] = $el;
unset($newArray[$oldKey]);
}
}
krsort($newArray);
This is perfectly working but this is very lengthy process because my array has thousands of elements. Thanks in advance for your help.
Try like this :-
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Like #saravanan answer but result sorted:-
<?php
$input = [['b'],['a'],['b'],['c'],['a'],['a'],['b'],['a']];
$result = array_count_values( array_map("serialize", $input));
arsort($result,SORT_NUMERIC);
$result = array_map("unserialize",array_keys($result));
print_r($result);

Explode a string into bidimensional array

Excuse me if this question was already solved. I've searched trough the site and couldn't find an answer.
I'm trying to build a bi-dimensional array from a string. The string has this structure:
$workers="name1:age1/name2:age2/name3:age3"
The idea is to explode the array into "persons" using "/" as separator, and then using ":" to explode each "person" into an array that would contain "name" and "age".
I know the basics about the explode function:
$array=explode("separator","$string");
But I have no idea how to face this to make it bidimensional. Any help would be appreciated.
Something like the following should work. The goal is to first split the data into smaller chunks, and then step through each chunk and further subdivide it as needed.
$row = 0;
foreach (explode("/", $workers) as $substring) {
$col = 0;
foreach (explode(":", $substring) as $value) {
$array[$row][$col] = $value;
$col++;
}
$row++;
}
$array = array();
$workers = explode('/', "name1:age1/name2:age2/name3:age3");
foreach ($workers as $worker) {
$worker = explode(':', $worker);
$array[$worker[0]] = $worker[1];
}
Try this code:
<?php
$new_arr=array();
$workers="name1:age1/name2:age2/name3:age3";
$arr=explode('/',$workers);
foreach($arr as $value){
$new_arr[]=explode(':',$value);
}
?>
The quick solution is
$results = [];
$data = explode("/", $workers);
foreach ($data as $row) {
$line = explode(":", $row);
$results[] = [$line[0], $line[1]];
}
You could also use array_walk with a custom function which does the second level split for you.
This is another approach, not multidimensional:
parse_str(str_replace(array(':','/'), array('=','&'), $workers), $array);
print_r($array);
Shorter in PHP >= 5.4.0:
parse_str(str_replace([':','/'], ['=','&'], $workers), $array);
print_r($array);
yet another approach, since you didn't really give an example of what you mean by "bidimensional" ...
$workers="name1:age1/name2:age2/name3:age3";
parse_str(rtrim(preg_replace('~name(\d+):([^/]+)/?~','name[$1]=$2&',$workers),'&'),$names);
output:
Array
(
[name] => Array
(
[1] => age1
[2] => age2
[3] => age3
)
)

How do I select last array per key in a multidimensional array

Given the following php array
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
how can I return only the last array per array key 'a'?
Desired result:
$new = array(
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
If I were you, I'd try to store it in a better format that makes retrieving it a bit easier. However, if you are stuck with your format, then try:
$a = array(
array('a'=>'111','b'=>'two','c'=>'asdasd'),
array('a'=>'111','b'=>'one','c'=>'sdvsdfs'),
array('a'=>'111','b'=>'three','c'=>'vbndfgn'),
array('a'=>'222','b'=>'nine','c'=>'dfhfnd')
);
$tmp = array();
foreach ($a as $value) {
$tmp[$value['a']] = $value;
}
$new = array_values($tmp);
print_r($new);

PHP merge array(s) and delete double values

WP outputs an array:
$therapie = get_post_meta($post->ID, 'Therapieen', false);
print_r($therapie);
//the output of print_r
Array ( [0] => Massagetherapie )
Array ( [0] => Hot stone )
Array ( [0] => Massagetherapie )
How would I merge these arrays to one and delete all the exact double names?
Resulting in something like this:
theArray
(
[0] => Massagetherapie
[1] => Hot stone
)
[SOLVED] the problem was if you do this in a while loop it wont work here my solution, ty for all reply's and good code.: Its run the loop and pushes every outcome in a array.
<?php query_posts('post_type=therapeut');
$therapeAr = array(); ?>
<?php while (have_posts()) : the_post(); ?>
<?php $therapie = get_post_meta($post->ID, 'Therapieen', true);
if (strpos($therapie,',') !== false) { //check for , if so make array
$arr = explode(',', $therapie);
array_push($therapeAr, $arr);
} else {
array_push($therapeAr, $therapie);
} ?>
<?php endwhile; ?>
<?php
function array_values_recursive($ary) { //2 to 1 dim array
$lst = array();
foreach( array_keys($ary) as $k ) {
$v = $ary[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge($lst,array_values_recursive($v));
}}
return $lst;
}
function trim_value(&$value) //trims whitespace begin&end array
{
$value = trim($value);
}
$therapeAr = array_values_recursive($therapeAr);
array_walk($therapeAr, 'trim_value');
$therapeAr = array_unique($therapeAr);
foreach($therapeAr as $thera) {
echo '<li><input type="checkbox" value="'.$thera.'">'.$thera.'</input></li>';
} ?>
The following should do the trick.
$flattened = array_unique(call_user_func_array('array_merge', $therapie));
or the more efficient alternative (thanks to erisco's comment):
$flattened = array_keys(array_flip(
call_user_func_array('array_merge', $therapie)
));
If $therapie's keys are strings you can drop array_unique.
Alternatively, if you want to avoid call_user_func_array, you can look into the various different ways of flattening a multi-dimensional array. Here are a few (one, two) good questions already on SO detailing several different methods on doing so.
I should also note that this will only work if $therapie is only ever a 2 dimensional array unless you don't want to flatten it completely. If $therapie is more than 2 dimensions and you want to flatten it into 1 dimension, take a look at the questions I linked above.
Relevant doc entries:
array_flip
array_keys
array_merge
array_unique
call_user_func_array
It sounds like the keys of the arrays you are generating are insignificant. If that's the case, you can do a simple merge then determine the unique ones with built in PHP functions:
$array = array_merge($array1, $array2, $array3);
$unique = array_unique($array);
edit: an example:
// Emulate the result of your get_post_meta() call.
$therapie = array(
array('Massagetherapie'),
array('Hot stone'),
array('Massagetherapie'),
);
$array = array();
foreach($therapie as $thera) {
$array = array_merge($array, $thera);
}
$unique = array_unique($array);
print_r($unique);
PHP's array_unique() will remove duplicate values from an array.
$tester = array();
foreach($therapie as $thera) {
array_push($tester, $thera);
}
$result = array_unique($tester);
print_r($result);

Categories