6

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?

4
  • 1
    Would you like to give us a look at an least an example of the array you are processing Commented Apr 27, 2018 at 21:06
  • @RiggsFolly edit my question adding the example. Commented Apr 27, 2018 at 21:17
  • no, the key that I want to assign to everything is '' quantity " Commented Apr 27, 2018 at 21:24
  • Interesting question Commented May 6, 2018 at 16:34

7 Answers 7

7
+25

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.

Sign up to request clarification or add additional context in comments.

1 Comment

....although why bother deserialilizing the JSON into a stdobject when you are treating as an array (you can deserialize to an array directly)
4

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.

Comments

2

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
        )

)

Comments

2

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
        )

)

Comments

1

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
            )

    )
    */

Comments

1

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);


Array
(
    [1] => Array
        (
            [12] => Array
                (
                    [ov] => 1
                    [ov2] => 2
                )

        )

    [2] => Array
        (
            [13] => Array
                (
                    [ov] => other values
                )

        )

)

Comments

-3

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

1 Comment

Please dont invent answer that have nothing to do with the question

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.