PHP - Output Dynamic Array Values In Json Array.
Hello all,
I have yet again trouble finding a logical solution to my problem. I'm fetching an array which can hold 1 or more values. The problem is, I want these values to ouput in my json_encode function, but this also needs to happen dynamically depending on the amount of values. I can't explain it further, so here's the code so far: Code: (php) [Select] $files = mysql_fetch_array($get_files); $a = count($files); $i = 1; while ($files) { $variablename = 'fileName' . $i; $$variablename = $files['fileName']; $i++; } $output = array( OTHER VALUES , 'fileName1' => $fileName1, 'fileName2' => $fileName2, 'fileName3' => $fileName3, ............); // How do I add the fileNames dynamically depending on how many there are? This got me thinking, I also need to dynamically GET the values with jQuery. How would I do that, when the above eventually works? Thank you. Similar Tutorialsi am trying to get values from the json array that get direct messages from twitter but i am getting the message error "Parse error: syntax error, unexpected T_AS, expecting '(' " in relation to the line "foreach (array as $direct_message) {" Also should i convert the array into a linear php array? Code: [Select] // create new instance $OAuth = new TwitterOAuth($consumer_key,$consumer_secret, $oAuthToken, $oAuthSecret); $direct_message = $OAuth->get('https://api.twitter.com/1/direct_messages.json?count=1&page='); function write_into_database ($direct_message) { $conn = mysql_connect("127.0.0.1", "Diego", "frafra") or die(mysql_error()); mysql_select_db('bot', $conn) or die(mysql_error()); foreach(array as $direct_message) { mysql_query("INSERT INTO 'followers' ('user_id', 'user_alias'), VALUES ('{$direct_message->sender_id}', '{$direct_message->sender_screen_name}, INSERT INTO 'd_messages'('message_id', 'message'), VALUES ('{$direct_message->id}' ,'{$direct_message->text})"); } write_into_database($direct_message); hello, i want to extract the sender_id, sender_alias and text from the array that should be returned when requesting access to direct messages via API. I get the error "Fatal error: Call to undefined method TwitterOAuth::request() " referring to the line $direct_message = $OAuth->request('GET', $OAuth->url('https://api.twitter.com/1/direct_messages.json'), array('sender_id','screen_name' ,'text')); Code: [Select] // create new instance $OAuth = new TwitterOAuth($consumer_key,$consumer_secret, $oAuthToken, $oAuthSecret); $direct_message = $OAuth->request('GET', $OAuth->url('https://api.twitter.com/1/direct_messages.json'), array('sender_id','screen_name' ,'text')); $direct_message = json_decode($OAuth->response['response'], true); echo response; I have mysql select query shown below retrieving data from a database:
$sql = " SELECT student, sum( test_score ) as score FROM test INNER JOIN level ON test.level_id = level.level_id GROUP BY student" $result = $mysqli->query($sql, MYSQLI_STORE_RESULT); if($result) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { var_dump($row); } }On inspection of the retrieved array with var_dump(), i have these result below: array (size=2) 'John' => string 'English' (length=2) 'Score' => string '20' (length=3) array (size=2) 'Mary' => string 'Math' (length=3) 'Score' => string '35' (length=3) array (size=2) 'Samuel' => string 'Physics' (length=3) 'Score' => string '5' (length=3)How do I get at and print out the highest score from this set of array values within this context. I tried this echo max($row['count']) but i understandably got this feedback: Warning: max(): When only one parameter is given, it must be an array Thanks. Hi there, Basic question, but I can't seem to find a page in the PHP docs that answers (though I'm sure such a one exists, I just can't seem to think up the right search terms - anyway) My question is: is there a short-hand way to use a value from an associative array as the key in another associative array? So for example, given this array: $the_array = array(0 => array('name': 'the_name', 'value' : 'the_value'), 1 => etc....); then this kind of foreach loop doesn't work Code: [Select] $new_data = array(); foreach($the_array as $element){ $new_data[$element['name']] = $element['value']; } Obviously I can just save out the values, like $name = $element['name'] --- but I was just wondering if there was a more efficient way to do it? Cheers, PS. I tried encapsulating with {} - i.e. $new_data[{$element['name']}] --- but that also fails. I need to some how pull comma separated images $data[23] from this $data array and then put them into there own array so I can insert them into separate rows in a database. This is the provided array: $data[0] => VIN $data[1] => StockNumber ...(all the other number here) $data[23] => Image_URLs (comma seperated) $data[24] => Equipment // I need something like this (obviously doesn't work?!@#) $delimiter = ","; $img = explode($delimiter, $data[23]); foreach($img as $pic){ $sqlPic = "insert into class_prodimages (pid image rank) values('".$LastId['id']."', '$pic', '".rand(1,20)."')"; } Any help here? I have an array created to control the down states of the my buttons in my navigation. Which is working well. This array will have quite a few strings in it before I'm done. I then want to conditionally load a CSS file for all the files in that array with the exception of two, is this possible? In plain in english I want to say If in array apart from these values then load my css file. My array (will have more values when complete) Code: [Select] $otherTitles = array('Product Selector', 'Avon Range', 'Knightsbridge Range', 'Kingston Range' ); My code to load a css file Code: [Select] <?php if (in_array($title, $otherTitles)) { ?> <link rel="stylesheet" type="text/css" href="homepage.css"/> <?php } ?> I want all titles in the otherTitles array to get this CSS file apart from two Product Selector and Avon Range. Thanks Richard I have the following array structu Code: [Select] [0] => Array ( [id] => Array ( [$t] => http://www.google.com/mate/ ) [updated] => Array ( [$t] => 2011-08-31T11:43:05.942Z ) [category] => Array ( [0] => Array ( [scheme] => http://schemas.google.com/g/ [term] => http://schemas.google.com/contact/ ) ) [title] => Array ( [type] => text [$t] => Name ) [link] => Array ( [0] => Array ( [rel] => http://schemas.google.com/contacts/2008/rel#edit-photo [type] => image/* [href] => https://www.google.com/mate/feeds/photos/media/ ) [1] => Array ( [rel] => self [type] => application/atom+xml [href] => https://www.google.com/mate/feeds/contacts ) [2] => Array ( [rel] => edit [type] => application/atom+xml [href] => https://www.google.com/mate/feeds/ ) ) [gd$email] => Array ( [0] => Array ( [rel] => http://schemas.google.com/g/2005#other [address] => email_address@gmail.com [primary] => true ) ) ) I am tried to display name and email address. I am using following method, can anyone tell me is there any better way? Thank u 4u help. NAME $name=( $emp_det[0]['title'][t]); $email =( $emp_det[0]['gdemail'][0][address]); Hello. I was wondering how can I add a php array to a js array containing json values.
var availableTags = [ "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme" ];I want to add this to the js array: <?php $arr = array('red', 'green', 'blue'); ?>I've tried doing this, but its definitely the wrong approach as it just sums everything up into one element "redgreenblue" var availableTags = [ "<?php foreach($arr as $row) { echo $row; } ?>", "AppleScript", "Asp", "BASIC", ....Thanks for any kind of help! Edited by Pain, 19 August 2014 - 05:17 PM. Hello there again!
I have the following construct of array now (schematics):
array[0] array[id] = "1" array[title] = "title" array[1] array[id] = "3" array[title] = "another title"Now what i want to do, is to assign the parent-array keys to the IDs of it's contents. This is what it should look like: array[1] array[id] = "1" array[title] = "title" array[3] array[id] = "3" array[title] = "another title"How do I do that again? I know I did this some years ago, but I can not remember how. I have a json file returned by facebook e.g { "data": [ { "name": "Support! Muffin the fool (Oldham Chronicle FAKE)", "category": "Community", "id": "181377645219010", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|181377645219010|MvOBJKYtO7eT8JxMLtJ00HtGNxo" }, { "name": "Northplanet", "category": "Local business", "id": "132483460132622", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|132483460132622|AHXPNTZx7aihyQS_A9W6pR115U4" }, { "name": "Social Media Manger", "category": "Application", "id": "102650199811234", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|102650199811234|KeH0n1OKzZFtCkpa0lX1yJZ7NBE" }, { "name": "Top Ten Things To Remember Me By!", "category": "Application", "id": "375102030458", "access_token": "102650199811234|060d3610d4dba63953209fa5-637782927|375102030458|H-mpQWrksu_2FzZ_eBNVzeD2Z1Y" } ] } $graph_url = "https://graph.facebook.com/$uid/comments=" . $access_token; $api = json_decode(file_get_contents($graph_url)); $name = $api->data->name; // this bit not storing the name not sure why I am writing a simple connector for an android application and my json_encode is outputting enclosing the array with []. This is throwing an error during the decode process because the array needs to start with a {. I know this has to do with the $output[] in the loop, but I dont know how to pass the values into the array any other way. I even tried to trim after doing the encode. Here is my code: Code: [Select] <?php require_once ('includes/config.php'); require_once ('includes/connect.php'); $agency= mysql_query("SELECT agencyname FROM agency WHERE status ='Prospect' ORDER BY agencyname DESC")or die(mysql_error()); while($ageinfo = mysql_fetch_assoc($agency)) { $output[] = $ageinfo; } print(json_encode($output)); ?> i am brand new to php and thought a project looking at the weather undergound api would be a great place to "cut my teeth" and i am following up on a recent post i saw here http://www.phpfreaks.com/forums/index.php?topic=354658.msg1675207#msg1675207 the responder excellently described how to use the foreach function however i am not sure this is right for my application the project i am trying to accomplish is defining the freeze thaw cycle for the next ten days which i can accomplish in excel but thought this is a good way to learn to code. so my question is how should i do this, i have tried and failed with trying to pick out individual highs and lows data and define them as above or below freezing but i can't figure out how to pick out the right number my code for this part of the project is $json_line = file_get_contents("http://api.wunderground.com/api/{key}/geolookup/forecast10day/q/$zipcode.json"); $parsed_line = json_decode($json_line); echo $parsed_json->{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'date'}->{'weekday'}; $temp_h = $parsed_line->{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'high'}->{'farenheit'}; $temp_l = $parsed_json->{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'low'}->{'farenheit'}; echo "Forecast for ${day} is:\n"; echo "High Temp is ${temp_h}<br />"; echo "Low Temp is ${temp_l}\n"; another road i was looking at going down was trying to do an array shift any help would be greatly appreciated thanks jeremy Havent posted here in a while, been learning lots but im stuck on trying to unset/replace arrays that contain awkward key values.
[0] => 2021-06-02T19:40:00Z [1] => 2021-06-03T02:10:00Z [2] => 2021-06-03T01:10:00Z [3] => 2021-06-02T23:05:00Z [4] => 2021-06-02T23:05:00Z [5] => 2021-06-02T23:07:00Z [6] => 2021-06-02T23:20:00Z [7] => 2021-06-02T18:20:00Z [8] => 2021-06-03T00:10:00Z [9] => 2021-06-03T00:40:00Z The json Im using is constantly updated, not sure why tmrw's dates June 3rd are at the top for their API design =[ Not good at regex. preg_replace/etc. Im desperate id use array search manually if I knew how to simple parse out tmrw's dates. I have unlimited API calls so I reckon it don't matter, here's what Ive been playing with $oddsdata = 'https://pinnacle.datafeeds.net/api/json/odds/pinnacle/v3/60/baseball/mlb/moneyline?api-key=a71b8fe8e9eb957db549aaa5d99797a4'; $readodds = file_get_contents($oddsdata); $odds = json_decode($readodds, true); $today = date("Y-m-d"); $tmrw = date('Y-m-d', strtotime( $today . " +1 days")); foreach($odds['games'] as $key => $val): $gidRE[$key]["gid"] = $val["gameUID"]; $startOdds[$key]["start"] = $val["startDate"]; $homeTeams[$key]["hteam"] = $val["homeTeam"]; $awayTeams[$key]["ateam"] = $val["awayTeam"]; $Price[$key]["betPrice"] = $val["betPrice"]; $BookOdds[$key]["book"] = $val["sportsbook"]; $BetName[$key]["betName"] = $val["betName"]; $Live[$key]["Live"] = $val["isLive"]; endforeach; $endgidd = end(array_keys($gidRE)) + '1'; $endz = end(array_keys($odds['games'])); for ($l = 0; $l < $endz; ++$l) { $OddsAll[] = array_merge($gidRE[$l], $startOdds[$l], $homeTeams[$l], $awayTeams[$l], $Price[$l], $BetName[$l]); }
Hello everyone. I'm a self learner that is very new to programming. I'm trying to print out the value of ["mid"] from a json_decode variable in the code shown below: I'm trying to use for each to access the value of "mid'. using foreach function. I know I'm not doing it the right way. please help me or show me an easy was to go around it. /////the json resopnd form the url is : {"terms":"http://www.xe.com/legal/dfs.php","privacy":"http://www.xe.com/privacy.php","from":"USD","amount":1.195,"timestamp":"2021-02-09T16:52:00Z","to":[{"quotecurrency":"NGN","mid":454.6559871014}]} ///////////////////////////////////////////////// <?php $auth = base64_encode("username:password"); $context = stream_context_create([ "http" => [ "header" => "Authorization: Basic $auth" ] ]); $homepage = file_get_contents("https://xecdapi.xe.com/v1/convert_from?to=NGN&amount=1.195", false, $context ); $json = json_decode($homepage, TRUE); foreach ($json as $price){ echo $price['mid']; }; ?>
Hi, I have been banging my head against a brick wall the past few days trying to figure this out after reading so many tutorial and forum post but I still can't figure it out. I would be very grateful if someone could help me out. Basically I am being supplied with this JSON Data structu $json='{ "countries": { "country": [ { "@attributes": { "Name": "Germany", "Lat": "52.6847077739394", "Lng": "-6.81976318359375", "ZoomLevel": "7" } }, { "@attributes": { "Name": "Sweeden", "Lat": "54.00131186464818", "Lng": "-7.36358642578125", "ZoomLevel": "8" } } ] } }'; I decode the JSON data structure as a PHP array and I print out the contents of the array for debugging purposes: $json_array=json_decode($json,true); print_r($json_array); Heres what the outputed array looks like: Code: [Select] Array ( [countries] => Array ( [country] => Array ( [0] => Array ( [@attributes] => Array ( [Name] => Germany [Lat] => 52.6847077739394 [Lng] => -6.81976318359375 [ZoomLevel] => 7 ) ) [1] => Array ( [@attributes] => Array ( [Name] => Sweeden [Lat] => 54.00131186464818 [Lng] => -7.36358642578125 [ZoomLevel] => 8 ) ) ) ) ) I want to be able to access all the country names contained in [Name] Can anyone please help me on how to do this correctly as I've tried lots of code with multi-dimensional arrays but I've had no luck. I am not able to acces the variable correctly. Thanks in advance. I have a simple ajax that passes data to a php script using jquery serialize. This is working good but where I am getting stuck is trying to pass json array into mysql. The json is outputting the correct data, but when I insert into db, it just says Array in the field. How can I convert(if that is the right term) json array to use in mysql. In the code I have posted, $box is an array from jquery which I normally use foreach to loop through array. What I need to do is convert $box after is has been encoded. Thanks Code: [Select] $box = $_POST['BRVbrtrv_boxnumber']; $list = array("activity" => $activity, "mobile" => $mobile, "company" => $company, "authorised" => $authorised, "service" => $service, "department" => $department, "address" => $address, "boxcount" => $boxcount, "box" => $box); $c = json_encode($list); echo $c; <?php ini_set('display_errors', 0); function escapeArray($array) { foreach ($array as $key => $val) { if(is_array($val)){ $array[$key]=escapeArray($val); } else{ $array[$key]=addslashes($val); } } return $array; } $request_type=$_SERVER['REQUEST_METHOD']; $api_key=$_SERVER['HTTP_X_API_KEY']; $res=array(); if($api_key!=="643256432"){ $res['msg']="Failu Invalid API KEY"; echo json_encode($res); die; } // Connects to the orcl service (i.e. database) on the "localhost" machine //$conn = oci_connect('SCOTT', 'admin123', 'localhost/orcl'); $conn = oci_connect('test', 'test', '192.168.10.43/test.test.com'); if (!$conn) { $e = oci_error(); trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); } $request=file_get_contents("php://input"); $request=escapeArray(json_decode($request,true)); print_r($request); // die; if($request_type=="POST"){//for creation of invoice echo $CONTACT_ID=isset($request['CONTACT_ID'])?$request['CONTACT_ID']:""; $INV_SERIAL_NO=isset($request['INV_SERIAL_NO'])?$request['INV_SERIAL_NO']:""; $NAME=isset($request['NAME'])?$request['NAME']:""; $INV_DATE=isset($request['INV_DATE'])?$request['INV_DATE']:""; $DUE_DATE=isset($request['DUE_DATE'])?$request['DUE_DATE']:""; $CURRENCY=isset($request['CURRENCY'])?$request['CURRENCY']:""; $SUBTOTAL=isset($request['SUBTOTAL'])?$request['SUBTOTAL']:""; $TAX_TOTAL=isset($request['TAX_TOTAL'])?$request['TAX_TOTAL']:""; echo $SHIP_SERIAL_NO=isset($request['SHIP_SERIAL_NO'])?$request['SHIP_SERIAL_NO']:""; $MASTER_NO=isset($request['MASTER_NO'])?$request['MASTER_NO']:""; $HOUSE_NO=isset($request['HOUSE_NO'])?$request['HOUSE_NO']:""; $shipment_data=isset($request['shipment_data'])?$request['shipment_data']:""; if($CONTACT_ID==""){ $res['msg']="CONTACT_ID is required"; } else if($INV_SERIAL_NO==""){ $res['msg']="INV_SERIAL_NO is required"; } else if($NAME==""){ $res['msg']="NAME is required"; } else if($INV_DATE==""){ $res['msg']="INV_DATE is required"; } else if($DUE_DATE==""){ $res['msg']="DUE_DATE is required"; } else if($CURRENCY==""){ $res['msg']="CURRENCY is required"; } else if($SUBTOTAL==""){ $res['msg']="SUBTOTAL is required"; } else if($TAX_TOTAL==""){ $res['msg']="TAX_TOTAL is required"; } else if($MASTER_NO==""){ $res['msg']="MASTER_NO is required"; } else if($HOUSE_NO==""){ $res['msg']="HOUSE_NO is required"; } else if($SHIP_SERIAL_NO==""){ $res['msg']="SHIP_SERIAL_NO is required"; } else{ $stid = oci_parse($conn, "Select * from FL_HDR_INVOICE where CONTACT_ID='$CONTACT_ID'"); (oci_execute($stid)); oci_fetch_all($stid, $out); if(count($out['CONTACT_ID'])==0){ $stid = oci_parse($conn, "Insert into FL_HDR_INVOICE (CONTACT_ID,INV_SERIAL_NO,NAME,INV_DATE,DUE_DATE,CURRENCY,SUBTOTAL,TAX_TOTAL) Values ('$CONTACT_ID','$INV_SERIAL_NO','$NAME',TO_DATE('$INV_DATE','YYYY-MM-DD'),TO_DATE('$DUE_DATE','YYYY-MM-DD'),'$CURRENCY','$SUBTOTAL','$TAX_TOTAL')"); oci_execute($stid); $stid_2 = oci_parse($conn, "Insert into FL_SHIPMENT_DATA (CONTACT_ID,INV_SERIAL_NO,SHIP_SERIAL_NO,MASTER_NO,HOUSE_NO) Values ('$CONTACT_ID','$INV_SERIAL_NO','$SHIP_SERIAL_NO','$MASTER_NO','$HOUSE_NO')"); oci_execute($stid_2); if(oci_num_rows($stid)>0){ $res['msg']="Invoice created successfully against this contact_id:".$CONTACT_ID; } else{ $res['msg']="Something going wrong please try again later"; } } else{ $res['msg']="contact_id must be unique"; } } echo json_encode($res); die; } I need to read json data inside an array. Please help correct my code.. i am trying to do an API. Hi, I have the following code that takes a list from a mySQL db and puts it into an array that shows 'gig date, venue, city' per entry: - Code: [Select] while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) { $array[] = ($row['date'].', '.$row['gl_venue'].', '.$row['gl_city']); } $output = json_encode($array); this outputs JSON like so: Code: [Select] ["06-05-2011, O'neills, Southend","07-05-2011, Power League, Peterborough","14-05-2011, Queen Victoria hall, Oundle",.......] how do I add keys into the array so I get something like: Code: [Select] {"gigs":[ { "gig": "date, venue, city",} ]} at least I think so anyway!?! What I want to do is eventually be able to parse a JSON listing into Objective-C and be able to call key/pairs into various different parts of an app. I'm pretty new to this so any advice would be great. Hello, Having a bit of a tough time understanding what is going on in my brain! I'm basically pulling some data from an API using CuRL, which is working fine. The structure of the data is: [data][tickets] - tickets being an array of support tickets in the system, which then contains ticketNumber, title, content. I want to display these values in a list, I have this code currently: if ($err) { echo "cURL Error #:" . $err; } else { $return = json_decode($response, true); foreach($return as $key) { echo $key["tickets"][1]['ticketNumber']." - "; echo $key["tickets"][1]['title']." - "; echo $key["tickets"][1]['content']; } } Which obviously returns the ticketNumber, title & content of the first support ticket in the array, but I want to loop through and display that information for each ticket! Can anyone advise as to where I am going wrong? I think I need to utilise the ["tickets"][x] but not sure how!
Thanks in advance! Steve
An affiliate marketer refers some products which are stored in a simple array. $all_items_sold = '{"7777":{"item":"hammer","price":"4.99"},"8888":{"item":"nail","price":"1.99"},"9999":{"item":"apple","price":"2.00"}}'; $referred_by_Affiliate = array('1234','8888','7777');
So, out of all the 3 items that sold, only 2 of them were referred by the affiliate marketer.
Currently I do this:
Is there a "best practices" way to accomplish this?
Thank you. |