PHP : Implode and get the keys of a multidimensional associative array [duplicate] - php

This question already has answers here:
PHP - Convert multidimensional array to 2D array with dot notation keys
(5 answers)
Closed 2 years ago.
I have a little problem. I want to transform this:
$array['page']['article']['header'] = "Header";
$array['page']['article']['body'] = "Body";
$array['page']['article']['footer'] = "Footer";
$array['page']['news']['header'] = "Header";
$array['page']['news']['body'] = "Body";
$array['page']['news']['footer'] = "Footer";
Into this:
$array['page.article.header'] = "Header";
$array['page.article.body'] = "Body";
$array['page.article.footer'] = "Footer";
$array['page.news.header'] = "Header";
$array['page.news.body'] = "Body";
$array['page.news.footer'] = "Footer";
The number of dimensions is variable and can be times 0 or 10. I don't know if I used the right search term, but Google could not help me so far.
So if someone has a solution for me.
Thanks

You can loop over the array at hand. Now, if the current value is an array, recursively call that array to the function call. On each function call, return an array with key value pairs. When you get the output from your sub-array, attach current key value to all keys of that sub-array returned output.
Snippet:
<?php
function rearrange($array){
$output = [];
foreach($array as $key => $val){
if(is_array($val)){
$out = rearrange($val);
foreach($out as $sub_key => $sub_val){
$output[$key . "." . $sub_key] = $sub_val;
}
}else{
$output[$key] = $val;
}
}
return $output;
}
print_r(rearrange($array));
Demo: https://3v4l.org/40hjK

Related

php: given a list of artists and have to determine which one has the longest name [duplicate]

This question already has answers here:
Read the longest string from an array in PHP 5.3
(3 answers)
Closed 2 years ago.
$array =array("AB","ABC","ABCD","ABCDE","BD");
Requirement: find the longest element in the array
Output:ABCDE
$array =array("AB","ABC","ABCD","ABCDE","BD");
$longstring = $array[0];
foreach( $array as $string ) {
if ( strlen( $string ) > strlen( $longstring ) ) {
$longstring = $string;
}
}
echo $longstring;
First we are iterate the array with help of foreach loop. in foreach loop we check $result is less than array value. if array value is greater then $result array then we override previous value of $result with new value. if we found greatest length than previous array element then we are storing new length & key of new element in variable.
$array =array("AB","ABC","ABCD","ABCDE","BD");
$result = $resultkey = 0;
foreach($array as $key=>$value) {
if($result < strlen($value) ) {
$result = strlen($value);
$resultkey = $key;
}
}
echo 'longest value:' $result;
echo 'result :' $array[$resultkey]
Output:
longest value: 5
result :ABCDE
You could sort the array by string length using strlen and usort and get the first item:
$array =array("AB","ABC","ABCD","ABCDE","BD");
usort($array, function($x, $y) { return strlen($y)-strlen($x); });
echo $array[0];
Result:
ABCDE
Demo
Try this, though it's a bit confusing.
<?php //php 7.0.8
$array = array("AB","ABC","ABCD","ABCDE","BD");
$longertext = array_search(max($array), $array)-1; //4-1 =3
// minus 1 because it's counting the actual position not starts with 0 it returns 4
echo $longertext; //equals 3
echo "\n";
echo $array[$longertext]; //equals ABCDE
?>
The actual test: http://rextester.com/OTI23127

I just started learning PHP. How to find and print the longest word in a PHP array [duplicate]

This question already has answers here:
Read the longest string from an array in PHP 5.3
(3 answers)
Closed 2 years ago.
$array =array("AB","ABC","ABCD","ABCDE","BD");
Requirement: find the longest element in the array
Output:ABCDE
$array =array("AB","ABC","ABCD","ABCDE","BD");
$longstring = $array[0];
foreach( $array as $string ) {
if ( strlen( $string ) > strlen( $longstring ) ) {
$longstring = $string;
}
}
echo $longstring;
First we are iterate the array with help of foreach loop. in foreach loop we check $result is less than array value. if array value is greater then $result array then we override previous value of $result with new value. if we found greatest length than previous array element then we are storing new length & key of new element in variable.
$array =array("AB","ABC","ABCD","ABCDE","BD");
$result = $resultkey = 0;
foreach($array as $key=>$value) {
if($result < strlen($value) ) {
$result = strlen($value);
$resultkey = $key;
}
}
echo 'longest value:' $result;
echo 'result :' $array[$resultkey]
Output:
longest value: 5
result :ABCDE
You could sort the array by string length using strlen and usort and get the first item:
$array =array("AB","ABC","ABCD","ABCDE","BD");
usort($array, function($x, $y) { return strlen($y)-strlen($x); });
echo $array[0];
Result:
ABCDE
Demo
Try this, though it's a bit confusing.
<?php //php 7.0.8
$array = array("AB","ABC","ABCD","ABCDE","BD");
$longertext = array_search(max($array), $array)-1; //4-1 =3
// minus 1 because it's counting the actual position not starts with 0 it returns 4
echo $longertext; //equals 3
echo "\n";
echo $array[$longertext]; //equals ABCDE
?>
The actual test: http://rextester.com/OTI23127

How to sorting array value by key? [duplicate]

This question already has answers here:
Custom key-sort a flat associative based on another array
(16 answers)
Closed 7 years ago.
I have array like this
<?php
$sliders=array(
1=>array('url'=>"url1.com",'image'=>"img1.jpg"),
2=>array('url'=>"url2.com",'image'=>"img2.jpg"),
3=>array('url'=>"url3.com",'image'=>"img3.jpg"),
4=>array('url'=>"url4.com",'image'=>"img4.jpg"),
5=>array('url'=>"url5.com",'image'=>"img5.jpg")
);
foreach($sliders as $sKey=>$sVal)
{
echo $sKey.'=>'.$sVal['url'].' image=>'.$sVal['image'].'<br>';
}
?>
And my sorting key is
$sort[]='2,4,5,3,1';
And I want result like this.
array(
1=>array('url'=>"url2.com",'image'=>"img2.jpg"),
2=>array('url'=>"url4.com",'image'=>"img4.jpg"),
3=>array('url'=>"url5.com",'image'=>"img5.jpg"),
4=>array('url'=>"url3.com",'image'=>"img3.jpg"),
5=>array('url'=>"url1.com",'image'=>"img1.jpg"));
How can I sorting Array like this?
Thanks.
I cannot believe that you did not find this yourself...
<?php
$newArray = array();
$sortArray = explode(',', $sort[0]);
$i = 1;
foreach ($sortArray as $s) {
if (isset($sliders[$s])) {
$newArray[$i] = $sliders[$s];
$i++;
}
}

How to join into a comma-separated string from array of arrays (multidimensional-array)? [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
Ok, I know that to get a comma-seperated string from a string array in PHP you could do
$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);
But what if I have an array of arrays(not a simple string array)?
$myAssociativeA =
array(
[0] => array("type"=>"cat", "sex"=>"male")
, [1] => array("type"=>"dog", "sex"=>"male")
);
and my goal is to get a comma-seperated string from a specific property in each array, such as "type"? Ive tried
$myGoal = join(',', $myAssociativeA{'type'});
My target value for $myGoal in this case would be "cat,dog".
Is there a simple way without having to manually loop through each array, extract the property, then do a join at the end?
This should work for you:
(Here I just get the column which you want with array_column() and simply implode it with implode())
echo implode(",", array_column($myAssociativeA, "type"));
Another option is to use array_walk() to return the key you want:
array_walk($myAssociativeA, function(&$value, $key, $return) {
$value = $value[$return];
}, 'type');
echo implode(', ', $myAssociativeA); // cat, dog
Useful for older PHP versions - #Rizier123's answer using array_column() is great for PHP 5.5.0+
You can use this if you have PHP < 5.5.0 and >= 5.3.0 (thanks to #Rizier123) and you can't use array_column()
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));
echo $myGoal;
?>
EDIT: with the recommendation in the comment of #scrowler the code now is:
<?php
$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';
$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));
echo $myGoal;
?>
Output:
cat,dog
Read more about array_map in:
http://php.net/manual/en/function.array-map.php
You just have to loop over the array and generate the string yourself.
<?php
$prepend = '';
$out = '';
$myAssociativeA = array(
array('type' => 'cat'),
array('type' => 'dog')
);
foreach($myAssociativeA as $item) {
$out .= $prepend.$item['type'];
$prepend = ', ';
}
echo $out;
?>
You could easily turn this into a function.
<?php
function implode_child($array,$key) {
$prepend = '';
$out = '';
foreach($array as $item) {
$out .= $prepend.$item[$key];
$prepend = ', ';
}
return $out;
}
?>
Ok, under assumption that your assoc array fields are ordered always the same way you could use snippet like this. Yet you still need to iterate over the array.
$csvString = "";
foreach ( $myAssociativeA as $row ) {
$csvRow = implode(",", $row);
$csvString .= $csvRow . PHP_EOL;
}
Now if you don't want to store whole CSV in a variable (which you should not do) take a look at http://www.w3schools.com/php/func_filesystem_fputcsv.asp and see an example how to put it directly into the file.

Converting 1D array to a 2D array with count of elements [duplicate]

This question already has answers here:
How to count the consecutive duplicate values in an array?
(6 answers)
Closed last month.
I'm stuck and am wondering if someone could point me in the right direction.
I have an array containing numbers, eg:
$start = array(0,0,0,45,45,0,3,0,0,1,1,1,1);
And would like that array to convert to this array:
$result = array( array('id'=>0, 'aantal'=>3,
array('id'=>45,'aantal'=>2),
array('id'=>0, 'aantal'=>1),
array('id'=>3,'aantal'=>1),
array('id'=>0, 'aantal'=>1),
array('id'=>1,'aantal'=>4)
)
I tried traversing the $start array, but I got stuck onlooking up the n-1 in $start without having the key.
Does anyone have any advice on how I can do this?
This would be the typical approach for run length encoding an array of items:
$array = array(0,0,0,45,45,0,3,0,0,1,1,1,1);
$last = null;
$current = null;
$result = array();
foreach ($array as $item) {
if ($item == $last) {
// increase frequency by 1
++$current['aantal'];
} else {
// the first iteration will not have a buffer yet
if ($current) {
$result[] = $current;
}
// create buffer array item, set frequency to 1
$current = array('id' => $item, 'aantal' => 1);
$last = $item;
}
}
// last pass
if ($current) {
$result[] = $current;
}

Categories