开发者

Stripping out numerical array keys from var_export

I want to do var_export() and strip out all numerical array keys on an array. My array outputs like so:

array (
  2 => 
  array (
    1 => 
    array (
      'infor' => 'Radiation therapy & chemo subhead',
      'PPOWithNotif' => '',
      'PPOWithOutNotif' => 'Radiation therapy & chemo PPO amount',
      'NonPPO' => 'Radiation therapy & chemo Non PPO amount',
    ),
  ),
  3 => 
  array (
    1 => 
    array (
      'infor' => 'Allergy testing & treatment subhead',
      'PPOWithNotif' => '',
      'PPOWithOutNotif' => 'Allergy testing & treatment PPO amount',
      'NonPPO' => 'Allergy testing & treatment Non PPO amount',
    ),
  )
)

By doing this I can shuffle the开发者_如何学Go array values however needed without having to worry about numerical array values.

I've tried using echo preg_replace("/[0-9]+ \=\>/i", '', var_export($data)); but it doesn't do anything. Any suggestions? Is there something I'm not doing with my regex? Is there a better solution for this altogether?


You have to set the second parameter of var_export to true, or else there is no return value given to your preg_replace call.


Reference: https://php.net/manual/function.var-export.php

return
If used and set to TRUE, var_export() will return the variable representation instead of outputting it.


Update: Looking back on this question, I have a hunch, a simple array_values($input) would have been enough.


May not be the answer you are looking for, but if you have a one level array, you can use the function below. It may not be beautiful, but it worked well for me.

function arrayToText($array, $name = 'new_array') {
  $out = '';
  foreach($array as $item) {
    $export = var_export($item, true);
    $export = str_replace("array (\n", '', $export);
    $export = substr($export, 0, -1);
    $out .= "[\n";
    $out .= $export;
    $out .= "],\n";
  }
  return '$' . $name . ' = ' . "[\n" . substr($out, 0, -2) . "\n];";
}

echo arrayToText($array);


This package does the tricks https://github.com/brick/varexporter

use Brick\VarExporter\VarExporter;
echo VarExporter::export([1, 2, ['foo' => 'bar', 'baz' => []]]);

Output:

[
    1,
    2,
    [
        'foo' => 'bar',
        'baz' => []
    ]
]


Why not just use array_rand:

 $keys = array_rand($array, 1);
 var_dump($array[$keys[0]]); // should print the random item

PHP also has a function, shuffle, which will shuffle the array for you, then using a foreach loop or the next / each methods you can pull it out in the random order.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜