-2

Hi I have a WordPress site with an array with elements in, and I when I loop through the array I want the fields to display in the order as it is set in the array. For example:

My array:

$metas = get_post_meta($post->ID);
$metatodisplay = array('address', 'county', 'postcode', 'region', 'telephone', 'fax', 'email', 'website', 'contact', 'cab_member_since', 'twitter', 'linkedin');

My foreach loop:

foreach($metas as $key=>$value){
   if(in_array($key, $metatodisplay)){
     echo $key;
   }    
}

I want the array values to display in the order as shown in the $metatodisplay array. At this point they are just random on several pages, and on others they display correctly.

I Love Code
  • 420
  • 1
  • 5
  • 26

1 Answers1

0

This should work:

foreach($metatodisplay as $key){
   if(isset($metas[$key])){
     echo $key;
   }    
}

Your code runs all values from $metas in their order and compares them to $metatodisplay (while the order of $metatodisplay is not taken into account). The changed code uses the exact order of $metatodisplay, ignoring the order within $metas.

If you want to do something with the values from $metas, you can simply accessing them, for example through echo $metas[$key]

Nico Haase
  • 11,420
  • 35
  • 43
  • 69
  • I need to also be able to display the values – I Love Code Jun 20 '18 at 12:01
  • In the original code, you have not outputted any values – Nico Haase Jun 20 '18 at 12:02
  • I just used a basic example of what I needed to sort, but I do need to also display the $value – I Love Code Jun 20 '18 at 12:03
  • Ah, you were looking for some kind of **sorting** algorihm based on the order of `$metatodisplay`? Why didn't you mention that in the first place? – Nico Haase Jun 20 '18 at 12:05
  • Look, I am not entirely experienced, quite new actually, I was just asking if there is maybe a function or some sort. I didn't know if I had to use a sorting algorithm, so I came to ask for advice here, not to get bashed about my question. Thank you for trying to help me. I will just ask my question in a better way later. And hopefully someone with more patience will be kind to guide me and also explain better. With Google while searching for sorting it kept giving me functions. Thanks. – I Love Code Jun 20 '18 at 12:12
  • Have a look at https://stackoverflow.com/questions/348410/sort-an-array-by-keys-based-on-another-array to find a solution to your problem. And I didn't want to bash you, but I could not guess that you needed more steps here and there than those you were asking for – Nico Haase Jun 20 '18 at 12:15
  • Thanks man, checking it out now, sorry if I was a bit sensitive – I Love Code Jun 20 '18 at 12:21