Sunday, May 6, 2018

Insert values into an associative array within a loop

Leave a Comment

I am new working with php, I am using a foreach loop to traverse an array of decoded objects. I would like to enter values to a new array for each iteration. This is a part of the code:

//example of array before decoding it [{"id":1,"quantity":12, other values...},{"id":2,"quantity":13,other values...}] $data = json_decode($request->data);  $newArray = array();  foreach ($data as $key => $value){   $newArray[$key] = $value->{'id'} //[1,2,3....] } 

at the moment I am generating a one-dimensional array, what I need is to obtain an array of this type:

[     1 => ['quantity' => $other],      2 => ['quantity' => $other] ] 

where 'other' would be another value that I get from my loop $value->{'other'}. How can I generate this?

8 Answers

Answers 1

I'm not 100% confident, whether I really got your question ... but this is probably what you want:

foreach ($data as $key => $value) {     $newArray[$value->id] = ['quantity' => $value->quantity]; }  print_r($newArray); 

after json_decode you have objects of type stdClass, so you can access the properties like shown above.

Answers 2

I am not sure why you need quantity keys in one element arrays. Without this you can simply use array_column function:

$items = json_decode($json); // $items = json_decode($json, true); // For PHP < 7.0  $result = array_column($items, 'quantity', 'id'); 

But if you sure that quantity keys are necessary you can map the result using array_map:

$result = array_map(function ($quantity) {    return ['quantity' => $quantity];  }, $result); 

Here is the demo.

Answers 3

Using a loop, you would do something like this:

$data = '[{"id":1,"quantity":12},{"id":2,"quantity":13}]'; $decoded = json_decode($data, $as_array = true); // decode as array, not object $accumulator = []; foreach($decoded as $index=>$values) {     $accumulator[$values['id']] = ['quantity' => $values['quantity']]; } print_r($accumulator); 

The same concept can be expressed more clearly in a functional manner with array_reduce:

$data = '[{"id":1,"quantity":12},{"id":2,"quantity":13}]'; $decoded = json_decode($data, $as_array = true); // decode as array, not object $reduced = array_reduce($decoded, function($carry, $entry){     $carry[$entry['id']] = ['quantity' => $entry['quantity']];     return $carry; }, $initial_value = []); print_r($reduced); 

Both approaches would generate the same output:

Array (     [1] => Array         (             [quantity] => 12         )      [2] => Array         (             [quantity] => 13         )  ) 

Answers 4

i think you are expecting like this,

$request = new stdClass(); $request->data = '[{"id":1,"quantity":12,"name":"item 1","code":"ITM-111"},{"id":2,"quantity":13,"name":"item 2","code":"ITM-222"}]';  $data = json_decode($request->data); $newArray = array();  print_r($data); 

example:

Array (     [0] => stdClass Object         (             [id] => 1             [quantity] => 12             [name] => item 1             [code] => ITM-111         )      [1] => stdClass Object         (             [id] => 2             [quantity] => 13             [name] => item 2             [code] => ITM-222         )  )  $other = 'name'; // required key  foreach($data as $value){     $newArray[$value->id] = [          'quantity' => $value->quantity,         'name' => $value->{$other}     ]; }  print_r($newArray); 

output :

Array (     [1] => Array         (             [quantity] => 12             [name] => item 1         )      [2] => Array         (             [quantity] => 13             [name] => item 2         )  ) 

Answers 5

You can do it using simple foreach loop

$json='[{"id":1,"quantity":12, "ov":1,"ov2":2},{"id":2,"quantity":13,"ov":"other values"}]'; echo "<pre/>"; $a=json_decode($json,TRUE); foreach($a as $val){     $arr=$val;     unset($arr['id']);     $new_arr[$val['id']]=$arr; } print_r($new_arr); 

Your question is not clear, if you are trying to put quantity on key , try something like below

$json='[{"id":1,"quantity":12, "ov":1,"ov2":2},{"id":2,"quantity":13,"ov":"other values"}]'; echo "<pre/>"; $a=json_decode($json,TRUE); foreach($a as $val){     $arr=$val;     unset($arr['id']);     $temp=$arr;     unset($temp['quantity']);     $new_arr[$val['id']]=[$arr['quantity']=>$temp]; } print_r($new_arr); 

Answers 6

First of all, you must decode into an array instead of an object. This is possibile with json_decode's second parameter as true.

$data = json_decode($request->data, true); 

Second, ... this solution is dirt but it works:

<?php  $request = new stdClass(); $request->data = '[{"id":1,"quantity":12,"foo":"bar"},{"id":2,"quantity":13,"fizz":"buzz"}]';  $data = json_decode($request->data, true); $newArray = array();  foreach ($data as $key => $value){     $other = $value;     unset($other['id']);     unset($other['quantity']);     $newArray[$value['id']] = [         'quantity' => $other,     ]; }  var_dump($newArray); 

And according to this example code:

[     1 => ['quantity' => $other],      2 => ['quantity' => $other] ] 

the result of this script is the following:

array(2) {   [1] =>   array(1) {     'quantity' =>     array(1) {       'foo' =>       string(3) "bar"     }   }   [2] =>   array(1) {     'quantity' =>     array(1) {       'fizz' =>       string(4) "buzz"     }   } } 

Answers 7

Here's how to generate the array as you described. I've added example values for the other property to help illustrate.

    <?php     header('Content-Type: text/plain');      $request_data = '[{"id":1,"quantity":12,"other":"Other 1"},{"id":2,"quantity":13,"other":"Other 2"}]';      $data = json_decode($request_data);     $newArray = array();      foreach ($data as $key => $value) {       $newArray[$value->id] = array(             'quantity' => $value->other         );     }      print_r($newArray);      // Returns:      /*     Array     (         [1] => Array             (                 [quantity] => Other 1             )          [2] => Array             (                 [quantity] => Other 2             )      )     */ 

Answers 8

You could append array using something like this:

foreach($file_data as $value) {     list($value1, $value2, $value3) = explode('|', $value);     $item = array(         'value1' => $value1,          'value2' => $value2,          'value3' => $value3     );     $file_data_array[] = $item; } 

For more informations, take a look at the following: Creating/modifying with square bracket syntax

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment