Torrie Posted September 8, 2017 Share Posted September 8, 2017 I'm so confused with multidimensional arrays. May I please ask a couple questions? 1.) In the json array below, How do I use PHP to echo, for example, the price offered by Susan? I tried things like echo $result["data"][0]["Susan"] to work, but it won't work. 2.) Near the top of the array it shows the lowest price is $25.56. How do I get PHP to echo that? Again, I tried echo $result[LowestPrice] but that doesn't work. 3.) The array below is really big. What code do I use to create a smaller array of just [Name] and [OfferingPrice] ?? If I can do that, then I can do the PHP thing where you go "foreach ($result as $var=>$value) { echo "$var...$value" } etc., and I can sort it etc. Here's the array: $result = json_decode($stuff,true); print_r($result); //this is what it is output Array ( [data] => Array ( [info] => Array ( [LowestPrice] => 25.56 [PlaceOfManufacture] => USA ) [OfferingPrice] => Array ( [0] => Array ( [OfferingPrice] => 20.00 [salesAssociate] => Array ( [badgeNumber] => 125 [Name] => Fred ) ) [1] => Array ( [OfferingPrice] => 18.36 [salesAssociate] => Array ( [badgeNumber] => 932 [Name] => Susan ) ) [2] => Array ( [OfferingPrice] => 2.34 [salesAssociate] => Array ( [badgeNumber] => 73 [Name] => Grandpa ) ) [3] => Array ( [OfferingPrice] => 44.28 [salesAssociate] => Array ( [badgeNumber] => 202 [Name] => Stewart ) ) ) ) ) Quote Link to comment Share on other sites More sharing options...
requinix Posted September 8, 2017 Share Posted September 8, 2017 If you have print_r() output of an array then you need to look at every "[...] =>" part between the top and the place you want. That means looking at the indentation, or at least navigating your way through the nested Array()s. 1. The price will be $result["data"]["OfferingPrice"][1]["OfferingPrice"]. The problem is the 1: if all you know is that the associate's name is Susan then you have to find a way to turn "the associate is Susan" into "the array key is 1". There are a few ways but the simplest is a foreach loop. foreach ($result["data"]["OfferingPrice"] as $offeringPrice) { if ($offeringPrice["SalesAssociate"]["Name"] == "Susan") { echo "Susan offered $", $offeringPrice["OfferingPrice"]; } }2. This one is easier. Array <- $result is an array ( [data] => Array <- $result["data"] is an array ( [Info] => Array <- $result["data"]["Info"] is an array ( [LowestPrice] => 25.56 <- $result["data"]["Info"]["LowestPrice"] is 25.563. Use a foreach loop like in #1 to make your own array. $smaller = array(); // empty foreach ($result["data"]["OfferingPrice"] as $offeringPrice) { $smaller[] = array( "Name" => // ??? "OfferingPrice" => // ??? ); }Try to fill in the ???s yourself - look at #1 for a hint. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.