Jump to content

How do I get specific things out of an array? Eg., make them into their own variable?


peterhuynh

Recommended Posts

Here is the code:

 

$ch = curl_init('some_api_information');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);

 

It prints this out:

 

{ "high":"8650.00", "last":"8500.00", "timestamp":"1410341807", "bid":"8310.00", "vwap":"8414.15", "volume":"107.05882350", "low":"8480.00", "ask":"8500.00" }

 

I want to make, e.g., "low", into a variable.

 

Thanks a bunch. I'm new to php.

Link to comment
Share on other sites

Yes I did. Thank you for the link. I studied it as much as I could. But I'd like to emphasize I'm a supernoob.

 

Some context:

the api grabs ticker infornation. So the results that it prints out isn't actually what I posted above; it will print out different results every time.

 

In the script you provided, you used the exact print out. So I don't think it will work out that way. Does that make sense?

 

Thanks,

P

Link to comment
Share on other sites

I was just giving an example on how json_decode() works.  Try the following.  The print_r() is just to show you what is happening.  Given some json, you use json_encode() to turn it into an array, and then you access the various array elements as you desire.

<?php
$ch = curl_init('some_api_information');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
$array=json_decode($result);
echo('<pre>'.print_r($array,1).'</pre>');
$low=$array['low'];
echo($low);
?>
Link to comment
Share on other sites

 

Given some json, you use json_encode() to turn it into an array, and then you access the various array elements as you desire.

 

I'm sure you just mispoke, but to be clear, you use json_decode() to turn it from a json string into a php array, not json_encode(), which is the opposite.

Link to comment
Share on other sites

 

I was just giving an example on how json_decode() works.  Try the following.  The print_r() is just to show you what is happening.  Given some json, you use json_encode() to turn it into an array, and then you access the various array elements as you desire.

<?php
$ch = curl_init('some_api_information');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
$array=json_decode($result);
echo('<pre>'.print_r($array,1).'</pre>');
$low=$array['low'];
echo($low);
?>

Hi, Thanks for your help.

 

I've been trying to figure out this stuff as I go, as to not keep asking people whenever I have a problem. But I couldn't figure it out.

 

When I try to echo $low, I get this message: "Fatal error: Cannot use object of type stdClass as array".

 

When I echo ('<pre>'.print_r($array,1).'</pre>'), I get this:

stdClass Object(    [high] => 285.50    [last] => 277.00    [timestamp] => 1423414632    [bid] => 275.00    [vwap] => 280.08    [volume] => 199.25328242    [low] => 274.69    [ask] => 277.00)
Link to comment
Share on other sites

By default, json_decode returns an object as you have done

$obj=json_decode($result);

So to access "low" you would use

$low = $obj->low;

If you want an array then you need the second argument of json_decode to be true EG

$array = json_decode($result, 1);

Then you can access low with

$low = $array['low'];
Link to comment
Share on other sites

 

By default, json_decode returns an object as you have done

$obj=json_decode($result);

So to access "low" you would use

$low = $obj->low;

If you want an array then you need the second argument of json_decode to be true EG

$array = json_decode($result, 1);

Then you can access low with

$low = $array['low'];

 

 

 

I was just giving an example on how json_decode() works.  Try the following.  The print_r() is just to show you what is happening.  Given some json, you use json_encode() to turn it into an array, and then you access the various array elements as you desire.

<?php
$ch = curl_init('some_api_information');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
$array=json_decode($result);
echo('<pre>'.print_r($array,1).'</pre>');
$low=$array['low'];
echo($low);
?>

 

Thanks, guys! I actually made something work in programming. :)

 

Is there a tipping service on this forums? If you guys have a bitcoin wallet, I'd like to send you something.

 

Another question: How do get specific things when the array is a set of sets?

 

For instance, my original problem was that I needed to get something out and turn it into a variable. The set looked like this: {"a":"1", "b":"2", "c":"3"}.

 

Now I need to get things that are members of a subset of the original set. E.g., {"bids": [[0.010010000, 150.000000000], [0.121000000, 82.000000000]], "asks": [[1700.000000000, 1.000000000],[282.365000000, 1.000000000]]}. Specifically, how do I get the lowest "asks"?

Link to comment
Share on other sites

 

is this the result you are looking for?

$results = '{"bids": [[0.010010000, 150.000000000], [0.121000000, 82.000000000]], "asks": [[1700.000000000, 1.000000000],[282.365000000, 1.000000000]]}';
$arr = json_decode($results, 1);
$asks = $arr['asks'];
sort($asks);
echo $asks[0][0];  //--> 282.365

 

Sorry, i was wrong about the contents of $results.

 

$results =

Response (example):
{“status”: ok | error,
“apirate”: apirate,
“message”: “” | error message,
“orderbook” :
{“bids”:
List [
List [
Pos 0 = Price
Pos 1 = Amount of currency per order
]
]
“asks”:
List [
List [
Pos 0 = Price
Pos 1 = Amount of currency per order
]
]
}
}

 

Link to comment
Share on other sites

You really got a response like that?  It doesn't appear to be valid JSON.

 

On a side note, I am going to stress that you use the following code often when starting off.  You could also use var_dump($array) which actually gives you more information, but the below is easier to read when you are new.

echo('<pre>'.print_r($myvariable,1).'</pre>');

For instance, maybe one of your variables includes something crazy like the below.  Where do you start?  Well, print_r first tells you that the top part is an object.  That means that you access properties using ->someobjectpropertier (as apposed to ['somearrayelement'] for an array).  someobjectpropertier and somearrayelement are just names I picked, and don't mean anything special.  As you go down, print_r tells you if it is an object, an array, or if neither, a string.

 

So, if I need something_I_need, I could use $myvariable->myarray['myobject']->something_I_need.  Make sure you understand this perfectly as you will be doing this often.

stdClass Object(    [high] => 8650.00    [last] => 8500.00    [timestamp] => 1410341807    [bid] => 8310.00    [vwap] => 8414.15    [volume] => 107.05882350    [low] => 8480.00    [ask] => 8500.00    [myarray] => Array        (            [high] => 8650.00            [last] => 8500.00            [timestamp] => 1410341807            [bid] => 8310.00            [vwap] => 8414.15            [volume] => 107.05882350            [low] => 8480.00            [ask] => 8500.00            [myobject] => stdClass Object                (                    [high] => 8650.00                    [last] => 8500.00                    [timestamp] => 1410341807                    [bid] => 8310.00                    [vwap] => 8414.15                    [volume] => 107.05882350                    [low] => 8480.00                    [ask] => 8500.00                    [something_I_need] => The Prize!                )        ))
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.