加入php对象键值

时间:2016-03-01 18:35:43

标签: php

我有这个对象:

stdClass Object
(
    [transaction] => sale
    [type] => apartment
    [city] => washington
    [rooms] => 1
)

我想连接键和值来获取字符串:

transaction-sale/type-apartment/city-washington/rooms-1

我设法用foreach()和空的var:

来做
$data = "";
foreach($obj as $key => $o):
    $data = $data."/$key-$o";
endforeach;

但这看起来很难看,我是否错过了任何可以轻松实现的核心PHP功能?

3 个答案:

答案 0 :(得分:2)

这不是此功能的目的,但这也有URL编码在URL中使用的变量和值的附带好处:

$data = str_replace('=', '-', http_build_query($object, null, '/'));

添加第二种方法,虽然这不是URL编码:

$data = implode('/', array_map(function($k, $v){
                                   return "$k-$v";
                               },
                               array_keys((array)$object), (array)$object));

答案 1 :(得分:1)

你可能不想要第一个或最后一个SELECT * from setpoints For each row SELECT io_id, io_value from io where io_id in (stpt_effective, stpt_actual, stpt_base); // these are from previous query ,也许它更像这样。

/
foreach($o as $k => $v){
  $a[] = "$k-$v";
}

echo implode('/', $a);
function foo($obj){
  foreach($o as $k => $v){ // this will fail if there are any more -public- variables declared in the class.
    $a[] = "$k-$v";
  }

  return implode('/', $a);
}

echo foo($yourobject);

或者像这样(或者上面的任何变体):

class foo{
  $transaction = 'sale';
  $type = 'apartment';
  $city = 'washington';
  $rooms = 1;

  function __tostring(){ // or a normal method name.
    foreach($self as $key => $value){ // this will fail if there are more variables declared in this class.
      $a[] = "$key-$value";
    }

    return implode('/', $a);
  }

  function bar(){ // will always work.
    return "transaction-{$self->transaction}/type-{$self->type}/city-{$self->city}/rooms-$self->rooms";
  }
}

echo $myobj;
echo $myobj->bar();

总的来说,我更喜欢第一种方法,但由于你有一个对象,所以实际上可以用它做一些事情。

答案 2 :(得分:0)

首先:http://php.net/manual/en/function.get-object-vars.php

将对象的成员作为关联数组获取,然后:http://php.net/manual/en/function.array-walk.php

这会给:

php > $o = new stdClass();
php > $o->transaction = "buy";
php > $o->type="house";
php > $o->city="Paris";
php > $o->rooms=2;
php > $a = get_object_vars($o);

然后我会使用http://php.net/manual/en/function.array-walk.php

php > function walk(&$value, $key) {
php { $value = "$key-$value";
php { }
php > array_walk($a, 'walk');
php > var_export(array_values($a));
array (
  0 => 'transaction-buy',
  1 => 'type-house',
  2 => 'city-Paris',
  3 => 'rooms-2',
)

编辑: 感谢您的评论:

php > echo implode("/", array_values($a));
transaction-buy/type-house/city-Paris/rooms-2