I have this array:
Array ( [#LFC] => 1 [#cafc] => 2 [#SkySports] => 1)
How do i display it like this on a page? (preferably in value descending order as below):
\#cafc (2), #LFC (1), #SkySports (1)
Thanks
First, sort the array
arsort($arrayName);
Next, iterate througth the array keys and values.
foreach($arrayName as $key => $value)
{
echo "$key ($value),";
}
Try using arsort to sort by descending value and then looping through the array, printing key/value pairs, as follows:
arsort($original_array);
foreach($original_array as $k => $v) {
echo $k.'('.$v.')';
}
if i got your question right, use a foreach loop in combination with arsort:
arsort($array);
foreach($array as $k => $v) {
printf('%s (%s)',
htmlspecialchars($k),
htmlspecialchars($v));
}
arsort($array);
$output = array();
foreach($array as $k => $v) {
$output[] = "$k ($v)";
}
print implode(", ", $output);
this will sort the array in reverse order, then create a new array with the data formatted the way you like, then implodes the output into a string separated by commas. The other answers so far will leave a dangling comma.
Related
I have the following array:
$names = array("Accounting"=>"Peter", "Finance"=>"Joe", "Human Resource"=>"Joe");
and want to output all keys and unique values.
The result should be:
Peter: Accounting
Joe: Finance, Human Resource
Thanks Philip
Create an empty array to hold the end result and use a simple foreach loop like this;
$names = array("Accounting"=>"Peter", "Finance"=>"Joe", "Human Resource"=>"Joe");
$resultArr = array();
foreach($names as $key => $value){
$resultArr[$value][] = $key;
}
// display $resultArr array
var_dump($resultArr);
Here's a live demo
Iterate through the keys and values in the array using a foreach loop and print both the keys and values.
foreach($names as $key => $value) {
print "$key : $value\n";
}
im trying to mix my multi dimension arrays, and it iterates fine, but the output isnt what im trying to accomplish, i need to mix the values.
array= [ [ p ,t ,j ] , [ 9 , 3 , 6 ] ];
foreach($array as $value) {
foreach($value as $key => $val) {
echo $val;
}
}
}
array output: p,9,t,3,j,6 //should be
Mine is: p,t,j,9,3,6
Simplest approach
foreach($array[0] as $key => $value) {
echo $value, $array[1][$key];
}
if i understand you this is your answer:
//creat an empty array to save the new result
$result= array();
//do this for incrementing
$i=0;
//your arrays here and looping it
$array=array(array( p ,t ,j ) , array( 9 , 3 , 6 ) );
foreach($array as $a){
if(is_array($a)){
foreach($a as $b){
$result[$i]= $b;
}//end foreach
}else{
$result[$i]= $a;
}//end else
$i++;
}//end foreach
//then print_r to show your array
print_r($result);
have a nice day ^_^
by 'mix' do you mean trying to combine the secondary arrays into one long array? If that is the case:
$finalArray = array();
foreach($array as $value) {
$finalArray = array_merge($finalArray, $value);
}
edit: now that I look at it, I didn't quite echo the output like you needed, but the output should be in the correct order in the $finalArray and this should work with any amount of inner arrays.
How can I get the list of values from my array:
[data] => Array
(
[5] => Array
(
[0] => 19
[1] => 18
[2] => 20
)
[6] => Array
(
[0] => 28
)
)
Expected output result string will be: 19,18,20,28
Thanks!
With one line, no loop.
echo implode(',', call_user_func_array('array_merge', $data));
Try it here.
Use following php code:
$temp = array();
foreach($data as $k=>$v){
if(is_array($v)){
foreach($v as $key=>$value){
$temp[] = $value;
}
}
}
echo implode(',',$temp);
Use following code.
$string = '';
foreach($yourarray as $k){
foreach($k as $l){
$string. = $l.",";
}
}
Just loop over sub arrays. Store values to $result array and then implode with ,
$result = array();
foreach ($data as $subArray) {
foreach ($subArray as $value) {
$result[] = $value;
}
}
echo implode(',', $result);
$data = array(5 => array(19,18,20), 6 => array(28));
foreach ($data as $array) {
foreach ($array as $array1) {
echo $array1.'<br>';
}
}
Try this one. It will help you
Since all of the data that you wish to target are "leaf nodes", array_walk_recursive() is a handy function to call.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
array_walk_recursive($data,function($v){static $first; echo $first.$v; $first=',';});
Output:
19,18,20,28
This method uses a static declaration to avoid the implode call and just iterates the call of echo with preceding commas after the first iteration. (no temporary array generated)
I haven't really taken the time to consider any fringe cases, but this is an unorthodox method that will directly provide the desired output string without loops or even generating a new, temporary array. It's a tidy little one-liner with a bit of regex magic. (Regex Demo) It effectively removes all square & curly brackets and double-quoted keys with trailing colons.
Code: (Demo)
$data=[5=>[19,18,20],6=>[28]];
echo preg_replace('/[{}[\]]+|"\d+":/','',json_encode($data));
Output:
19,18,20,28
To be clear/honest, this is a bit of hacky solution, but I think it is good for SO researchers to see that there are often multiple ways to achieve any given outcome.
try with this..
foreach($data as $dataArr){
foreach ($subArray as $value) {
$res[] = $value;
}
}
echo implode(',', $res);
Just use nested foreach Statements
$values = array();
foreach($dataArray as $key => $subDataArray) {
foreach($subDataArray as $value) {
$values[] = $value;
}
}
$valueString = implode(',', $values);
Edit: Added full solution..
How would I iterate through an array (300+ items, imported via simplexml) and pull out every item that has a certain $x->channel->item->title and put that into a different array?
I can't make heads or tails of the haystack needle thing or how to push arrays
Say I have an array (needle) like: array("3332","3300","3493","8380") and I want to match if any of those appear through the big array (haystack). How do I do this?
You have to iterate over your big array, and check for the value of $x->channel->item->title. If it meets your criteria, push it into the new array:
$theArray; // Your 300+ array
$lookFor = array('firstthing', 'second thing', 'third thing');
$newArray = array();
foreach($theArray as $x) {
if ( in_array($x->channel->item->title, $lookFor) ) {
array_push($newArray, $x);
}
}
foreach($yourArray as $key => $value)
{
//do your things with $key and/or $value
}
Modifying from Joseph's loop, you can do:
$theArray; // Your 300+ array
$newArray = array();
$matchArray = array("3332","3300","3493","8380");
foreach($theArray as $x) {
if (in_array($x->channel->item->title, $matchArray)) {
array_push($newArray, $x);
}
}
Check out in_array() at http://php.net/manual/en/function.in-array.php
So here is my code:
<?php
$arr = array(array(2 => 5),
array(3 => 4),
array(7 => 10));
foreach ($arr as $v) {
$k = key($v);
if ($k > 5) {
// unset this element from $arr array
}
}
print_r($arr);
// now I would like to get the array without array(7 => 10) member
As you can see, I start with an array of single key => value arrays, I loop through this array and get a key of the current element (which is a single item array).
I need to unset elements of the array with key higher than 5, how could I do that? I might also need to remove elements with value less than 50 or any other condition. Basically I need to be able to get a key of the current array item which is itself an array with a single item.
foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}
It is safe in PHP to remove elements from an array while iterating over it using foreach loop:
foreach ($arr as $key => $value) {
if (key($value) > 5) {
unset($arr[$key]);
}
}
Use key() to get the first key from the sub-array.
foreach($arr as $k => $v) {
if(key($v) > 5) {
unset($arr[$k]);
}
}
It's not really safe to add or delete from a collection while iterating through it. How about adding the elements you want to a second array, then dumping the original?
To unset array element we Used unset() and php function like below:
foreach($array as $key=>$value)
{
if(key($value) > 5)
{
unset($array[$key]);
}
}