X
X
xanatos372016-01-15 05:43:05
PHP
xanatos37, 2016-01-15 05:43:05

How to combine multiple values ​​with the same $key in different foreach into one variable?

there is json

$str = '{
      "message":"Privet mir",
      "channels": [
        {
          "id":"116",
          "logo":"3.png",
          "name":"STS",
          "city":"Beg"
        },
        {
          "id":"63",
          "logo":"2.png",
          "name":"REN",
          "city":"Tel"
        }
      ]
    }';

I retrieve the data like this:
$cart = json_decode( $str );

f (is_array($cart->channels)){
  foreach($cart->channels as $key => $city) {
    echo $city->city, $key . "\n";	
  }
  foreach($cart->channels as $key => $name) {
    echo $name->name, $key . "\n";	
  }
}   с

How to combine city and name with the same $key in one variable?
to be something like this
$data = "STS", "Beg"  // $key=0
$data1 = "REN", "Tel" //  $key=1

etc

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Muhammad, 2016-01-15
@xanatos37

foreach ($cart->channels as $channel) {
    echo $channel->name, $channel->city, PHP_EOL;
}

W
wol_fi, 2016-01-15
@wol_fi

$mergedArray = array();
foreach($array1 as $key=>$value) {
   if (!is_array($mergedArray[$key])) {
       $mergedArray[$key] = array();
   }
   $mergedArray[$key][] = $value;
}
foreach($array2 as $key=>$value) {
   if (!is_array($mergedArray[$key])) {
       $mergedArray[$key] = array();
   }
   $mergedArray[$key][] = $value;
}

so, no?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question