1

I have a JSON Array

    [0] => Array
    (   
        [stage_id] => 80    
        [yieldVal] => Array
            (
                [0] => Array
                    (
                        [datajson] => [{"name":"doi","value":"215"},{"name":"dateofpollinationstops","value":"Date of Pollination Stops~23-3-2015"}]
                    )

                [1] => Array
                    (
                        [datajson] => [{"name":"doi","value":"698"},{"name":"dateofpollinationstops","value":"Date of Pollination Stops~23-3-2015"}]
                    )
            )
    )   

I need to extract the values from this Array

    [0] => Array
    (   
        [stage_id] => 80    
        [yieldVal] => Array
            (
                [doi_value] => 215  
                [doi_value] => 698  
            )
    )   

I have tried decoding the JSON. But unable to continue further.

$phpArray = json_decode($res['datajson'], true);

How to extract the values and assign the key.

EDIT : My final output should be

[0] => Array
    (   
        [stage_id] => 80    
        [yieldVal] => 913  //215+698  -> Extracting values from [datajson]
    )
5
  • What's the output of var_dump($phpArray);? Commented Mar 27, 2015 at 10:57
  • 2
    You can't have multiple elements with the same key doi_value in an array. Commented Mar 27, 2015 at 10:58
  • @D4V1D its showing null.. Commented Mar 27, 2015 at 11:01
  • Infact i need to sum those values @Barmar Commented Mar 27, 2015 at 11:01
  • So you don't want an array in the resulting yieldVal? Please update the question to show what you really want. Commented Mar 27, 2015 at 11:02

2 Answers 2

1

One thing that may of tripped you up is that your datajson string is:

`[{"name":"doi","value":"215"},{"name":"dateofpollinationstops","value":"Date of Pollination Stops~23-3-2015"}]`

The square brackets mean that json_decode will create an array from the objects.

Anyway, try this...should give you the exact output you asked for:

$yieldVal = 0;

foreach ($res['yieldVal'] as $key => $arr) {

    $decode = json_decode($arr['datajson']);
    $yieldVal = $yieldVal + $decode[0]->value;

}

$newArray = array (

    'stage_id' => $res['stage_id'],
    'yieldVal' => $yieldVal

);

//var_dump($newArray);
echo "<pre>".print_r($newArray, true)."</pre>";
Sign up to request clarification or add additional context in comments.

Comments

1

You should be able to get the value with:

$doi_value = $phpArray[0]['value'];

You can then sum them, push them onto a resulting array, or whatever.

Comments

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.