Home > OS >  How can I use array values as keys?
How can I use array values as keys?

Time:08-29

I have an array named $stat that looks like this:

Array
(
    [0] => OK MPD 0.23.5
    [1] => repeat: 0
    [2] => random: 0
    [3] => single: 0
    [4] => consume: 1
    [5] => partition: default
    [6] => playlist: 11292
    [7] => playlistlength: 1
    [8] => mixrampdb: 0
    [9] => state: play
    [10] => song: 0
    [11] => songid: 3
    [12] => time: 14992:0
    [13] => elapsed: 14992.067
    [14] => bitrate: 48
    [15] => audio: 44100:16:2
    [16] => OK
)

I want to be able to use the array values (before the ":") as variables, instead of the numeric keys.

I need to do this, because the array keys returned change according to the player mode.

I have tried various methods, however I sense that my knowledge of PHP is simply not good enough to arrive at a solution.

The closest I have got is this:

foreach($stat as $list) {
        $list = trim($list);
//      echo "$list,";
        $list = "{$list}\n";
        $list = str_replace(": ", ",", $list);
        $xyz = explode(',', $list);
        $a=($xyz['0']);
        $b=($xyz['1']);
        echo "{$a}={$b}";
}

Which gives me this:

repeat=0
random=0
single=0
consume=1
partition=default
playlist=11642
playlistlength=1
mixrampdb=0
state=play
song=0
songid=3
time=15458:0
elapsed=15458.422
bitrate=50
audio=44100:16:2

If I try to create an array with the above output in the foreach loop, I end up with a multidimensional array which I can't seem to do anything with.

Can anyone help please?

CodePudding user response:

Not 100% sure if I understand what you want, but something like this perhaps:

// Init new empty array
$newStat = [];

foreach ($stat as $value) {
        $value = trim($value);
        // It is not really necessary to replace this, but I kept it as is
        $value = str_replace(": ", ",", $value);
        $split = explode(',', $value);
        $key = $split[0];
        $newValue = $split[1];

        // Add to empty array
        $newStat[$key] = $newValue;
}

echo $newStat['time']; // 15458:0

// You can also do
foreach ($newStat as $key => $value) {
    // Whatever you want
}

CodePudding user response:

function parseArray(array $array): array
{
  foreach($array as $value) {

    // IF the value is s string otherwise no cant do...
    if(is_string($value)) {

      // If we have a value after : otherwise set to null
      if(! str_contains($value, ':')) {
        $new[$value] = null;
        continue;
      }
    
      // Get data before ":" token as key and value after it.
      $key = substr($value, 0, strpos($value, ':'));
      $value = trim(str_replace($key.':', '', $value));
    
      $new[trim($key)] = $value;
    }
  
  }

  return $new ?? [];
}

  • Related