1

These are my code blocks that I write:

$url = "http://links";
        $curl_post_data = array(
          "username" => "guest",
        );
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_PORT, 8889);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
$result = $curl_response;
echo $result

What I did try is echo the $result variables and returned as bellow:

  {
        "price": [
            {
                "price": "2000",
                "origin_name": "JPN",
            },
            {
                "price": "5000",
                "origin_name": "USA",
            }
        ]
   }

What I want and need to know is how can I get or access the value of each elements which is the price and origin_name. I've try to call it with $result[0]['price']['origin_name'][0] but it doesn't work and returning like below:

Warning: Illegal string offset 'price' in .... on line ...

Warning: Illegal string offset 'origin_name' in .... on line ... 
{

I have also try using foreach function written like bellow:

foreach($result['price'] as $res){
            echo $res[0];
} 

but it's returning same error message:

Warning: Illegal string offset 'price' in .... on line ...

Warning: Invalid argument supplied for foreach() in  .... on line ... 
Digitorix
  • 23
  • 4
  • Post your entire code – user2342558 Jan 26 '18 at 09:18
  • Could the returned data be a JSON String? It looks like one – RiggsFolly Jan 26 '18 at 09:19
  • `$result = {` is not a normal PHP syntax, is it a json string instead? – Stanley Cheung Jan 26 '18 at 09:22
  • 1
    Except that the JSON is InValid – RiggsFolly Jan 26 '18 at 09:24
  • So first you need to get the site that is producing this JSON result to fix it so that JSON is valid. Is this result produced by your code or someone elses? – RiggsFolly Jan 26 '18 at 09:26
  • @user2342558 I did rewrite the whole completion – Digitorix Jan 26 '18 at 09:36
  • Then ask another question, as this has been put on hold. Show us how you create this JSONString in you API – RiggsFolly Jan 26 '18 at 09:38
  • 1
    @RiggsFolly I rewrite the code. So basically I use the curl to get all the data from the link api that provided, so the json result structure is written by someone else – Digitorix Jan 26 '18 at 09:39
  • To the powers that be, pls re-open the question. The provided links are not so helpful. First of all, what does one do when one receives data that is poorly formatted? Instead of manually fixing it, you can use PHP to get it in shape so that it constitutes valid JSON for PHP to then decode. After that, traverse the new PHP array with array_walk_recursive() (a solution not mentioned in the pertinent duplicate answered question). This real-world type of question requiring multiple solutions ought to be re-opened. – slevy1 Jan 26 '18 at 10:53
  • Then you should contact the producer of the data and ask them to fix their API! – RiggsFolly Jan 26 '18 at 11:42
  • It appears that your API provider is supplying you with a strange "comma-saturated pretty-printed json string". This is unfortunate for you. You either need to compel them to fix up the json being delivered, or use an unstable repairing method. I just happened to whack one together for you. (It will work until it doesn't ...yeah, that's what I just said) http://sandbox.onlinephpfunctions.com/code/391b30b9094fe82f2f62682f7950ea55582fc43b ...Hmm, actually, it looks like this: http://json5.org/ have a look. – mickmackusa Jan 27 '18 at 08:58
  • @deceze Are we looking at JSON5 here? I don't see a json5 tag on SO. – mickmackusa Jan 27 '18 at 09:05
  • @mickmackusa Your guess is as good as mine, OP needs to clarify and perhaps consult the producer of that data. – deceze Jan 27 '18 at 10:35
  • @RiggsFolly The thing is that's all the format that I got from the api and sadly the producer of the data probably won't fix the data since that api have been used by a lot of other corporations for a long time. – Digitorix Feb 02 '18 at 10:01
  • @deceze not sure what that format is called. – Digitorix Feb 02 '18 at 10:03
  • @mickmackusa the sad thing is producer of that data won't fix the format since it have been used by a lot of other corporations for a long time. – Digitorix Feb 02 '18 at 10:04
  • I think the green tick is poorly awarded then (since it won't work). slevy1's replacement pattern doesn't look right to me. I recommend that you limp your way through this unfortunately situation with my replacement regex pattern. I will not be 100% reliable, but it will cover the vast majority of cases. – mickmackusa Feb 02 '18 at 10:08
  • @deceze it seems this question is now asking: What do I do with this malformed json string since I can't control its creation? Should this be re-opened or closed differently? – mickmackusa Feb 02 '18 at 10:11
  • 1
    @mickmackusa It would need to be rewritten to be reopened, but since there are already answers here, rewriting the question would hose this entire thread. So, if that's really the question that needs answering, a new question shall be posted. – deceze Feb 02 '18 at 10:15

2 Answers2

2

Let assume from the beggining :

$result = '{
    "price": [
        {
            "price": "2000",
            "origin_name": "JPN"
        },
        {
            "price": "5000",
            "origin_name": "USA"
        }
    ]
}';
$resultDecoded = json_decode($result, true);
foreach ($resultDecoded["price"] as $item) {
    echo $item["price"];
}

The problem is the JSON String denotes an object, not an array

NOTE:

The JSON String you showed us was malformatted, no comma should be added at the end of the last Property of a JSONString Object.

Community
  • 1
  • 1
Ngob
  • 446
  • 4
  • 11
0

Sometimes the result one gets back needs fixing before using it. One can use preg_replace() to fix the invalid JSON. After decoding the remedied JSON into a PHP associative array, one can use array_pop() to extract the price array and then use array_walk_recursive() to fetch the price and origin name information, as follows:

<?php
// take badly formatted JSON ...
$result = '{
        "price": [
            {
                "price": "2000",
                "origin_name": "JPN",
            },
            {
                "price": "5000",
                "origin_name": "USA",
            }
        ]
   }';

// ... and remove the superfluous commas:
$pat = "/(o.+),/";
$replace = "$1";
$nu_result = preg_replace($pat,$replace,$result);

// now convert JSON into PHP array and traverse it
$resultDecoded = json_decode($nu_result, true);
$arr = array_pop($resultDecoded);
array_walk_recursive($arr,function($e,$i) {
       if ($i == "price") {
            echo "price: ",$e,"\n";
       }
       else
       if ($i == "origin_name") {
           echo "origin_name: ",$e,"\n\n";
       }
});

See live code

slevy1
  • 3,797
  • 2
  • 27
  • 33