0

I have a JSON array like this:

"custom_fields": [
    {
        "label": "Customer_Info",
        "data": "10"
    },  
    {   
        "label": "Customer_Other",
        "data": "50"
    }

I am able to access the data and print it like this:

$data = $_POST['custom_fields'];

foreach ($data as $item) {
    $line = '';
    foreach ($item as $key => $value) {
        if ($key == 'data'){
            $line .= "$key: $value, ";
        }
    }
    $current .= rtrim($line, ', ')."\n";
}

And then I get an output like:

data: 10
data: 50

Problem is, I want to get only the data value where the label is Customer_Info so that I just have a string with the value 10. How do I do that?

Any help is greatly appreciated before I lose the last few remaining hairs :/

4
  • Prepend if ($key == 'label' && $value != 'Customer_Info') continue; into inner foreach? Commented Jan 16, 2019 at 15:46
  • @Cobra_Fast what if, for some reasons, data is before label ? Commented Jan 16, 2019 at 15:51
  • @Cid fair point. Commented Jan 16, 2019 at 15:53
  • @Cobra_Fast Thanks for your help, too. The API where I get the data from isn't supposed to change, but you never know.. Commented Jan 16, 2019 at 15:59

2 Answers 2

1

You don't need to nest loops. 1 foreach is enough. Check the values in $item

$data = array(array("label" => "Customer_Info",
                    "data" => "10"),
              array("label" => "Customer_Other",
                    "data" => "50"));

$line = '';
foreach ($data as $item)
{
    if (isset($item['label'])
        && isset($item['data'])
        && $item['label'] == 'Customer_Info')
    {
        $line .= "data: {$item['data']}, ";
    }
}
$current = rtrim($line, ', ')."\n";
echo $current;

Output :

data: 10

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

Comments

0

If there will be only one with a label of Customer_Info, it would be easier to extract the data values and index on the label values:

echo array_column($data, 'data', 'label')['Customer_Info'];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.