1

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.

3 Answers 3

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

0
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 ?? [];
}

Comments

0

With a focus on direct programming, looped preg_match() calls will concisely qualifying and extract data to be used as key-value pairs in the result array.

The pattern capture one or more non-colon characters, then matches the delimiting colon and space, then captures zero or more characters until the end of the string.

Code: (Demo)

$result = [];
foreach ($array as $v) {
    if (preg_match('/([^:]+): (.*)/', $v, $m)) {
        $result[$m[1]] = $m[2];
    }
}
var_export($result);

Similarly, sscanf() can be used to parse the qualifying values as well. Note that %s will stop its greedy matching just before a whitespace character. Demo

$result = [];
foreach ($array as $v) {
    if (sscanf($v, '%[^:]:%s', $k, $v) === 2) {
        $result[$k] = $v;
    }
}
var_export($result);

As a funky, one-liner alternative, you can filter the array (to remove the values with no semicolons), replace the delimiting colon-space with an =, the implode with newlines, then parse the string-type payload as an ini string. This however demands that none of your string contain a newline or equals symbol. (Demo)

var_export(
    parse_ini_string(
        implode(
            "\n",
            preg_filter('/^[^:]+\K: /', '=', $array)
        )
    )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.