I am using simplehtmldom to parse a webpage and extract a data and then put it in a mysql database. I successfully extracted the data and put it in array but now the problem i am facing is how to convert this array to variable so that I may use it in my database query to insert the record in the specific fields. I want to convert array to individual variables
here is the code
<?php
include("simple_html_dom.php");
$html = file_get_html('abc.html');
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$item['title'] = trim($event->find('td', 1)->plaintext);
$sched[] = $item;
}
var_dump($sched);
?>
and the output is
array (size=6)
0 =>
array (size=1)
'title' => string 'Network admin, field engineer, engineering analyst, sales executive, PA to HR director Required by Telecommunication Company' (length=124)
1 =>
array (size=1)
'title' => string 'Karachi, Hydrabad, Lahore, Rawalpindi, Peshawar, Multan, Faisalabad' (length=67)
2 =>
array (size=1)
'title' => string '5 - 6 Years' (length=11)
3 =>
array (size=1)
'title' => string 'Knowledge of Field' (length=18)
4 =>
array (size=1)
'title' => string '' (length=0)
5 =>
array (size=1)
'title' => string '- Salary and incentives are not full and final. Can be discussed on final interview.
Can please somebody help me in achieving it. Thanks in advance
Well, if this needs to go in specific fields then you can do something like this:
INSERT INTO table_name (column1, column2, column3,...)
VALUES ($sched[0]['title'], $sched[1]['title'], $sched[2]['title'],...);
Php has a function for getting individual variables, extract() http://php.net/manual/en/function.extract.php
However I don't know why you would do that instead of just using a loop to go though your array.
You mean somethign like
foreach($sched as $item) {
$title = $item['title'];
insert_into_db($title);
}
?
Why do you want to move data from one perfectly good location i.e. the array into a scalar variable.
Double your memory usage for no actual reason.
I assume you are going to want to store the title's in a table
So you can :
foreach ( $sched as $one_sched ) {
// do your database update using $one_sched['title'] as the data identifier.
}
Why not use the array values directly? Also to me it makes no sense to build a subarray where every field is called title.
$sched = array();
foreach ( $html->find('tr[class=highlight-darkgrey]') as $event ) {
$sched[] = trim($event->find('td', 1)->plaintext);
}
Then access the values like:
$value0 = $sched[0];
$value1 = $sched[1];
// PDO example
$sth = $dbh->prepare(
'INSERT INTO table VALUES (?, ?, ...)'
);
$sth->execute(array($sched[0], $sched[1], ...));
// or if array count is right
$sth->execute($sched);
Related
array (size=2) //top array containg an other arrays
0 =>
array (size=2) //array containing 2 index
'content' => string ' The Lion King ' (length=33)
'slide_style' => string '' (length=0)
1 =>
array (size=2)
'content' => string ' Current fruit : mana bhanya the =
'slide_style' => string '' (length=0)
2 =>
array (size=2)
'content' => string ' Current fruit : mana bhanya the king
'slide_style' => string '' (length=0)
i have that structure of array please tell me how i can access data in my view file
Let's say that your top array is $array.
You could loop through the array to access each inner array and its items:
foreach($array as $inner_array) {
echo $inner_array['content'];
echo $inner_array['slide_style'];
}
Or to access certain values of inner arrays directly without looping through the top array, you could do this:
echo $array[0]['content'];
echo $array[0]['slide_style'];
Within this second method, you can swap out the 0 for whichever inner array you want to access (0 being the first, 1 being the second and so on).
Hope this helps.
You pass that array as a second argument to $this->load->view().
For example, you have a view page called posts.php and you pass data to it via controller like the following:
$data['posts'] = $this->post_model->getPosts();
$this->load->view('posts.php', $data);
and you access it in the view page posts.php like:
foreach($posts as $post) {
// Here the other code goes ...
}
Like you mentioned in the comment, if you want to loop through the array, this is the code you might be looking for:
foreach($posts as $post) {
echo "<h2>{$post['title']}</h2>";
echo "<p>{$post['description']}</p>";
}
This is how you access multi-dimensional array.
Hope you got it.
I'm trying to write an INSERT SQL request to populate a table of my db with a multidimensional array.
The array use the session variables (it's a shopping cart) $_SESSION['panier'], and currently has the following content :
array (size=3)
'ARTCOD' =>
array (size=2)
0 => string 'NA1818BLCFEZ' (length=12)
1 => string 'SER5151BLCFEZ' (length=13)
'COLLIB' =>
array (size=2)
0 => string 'blanc' (length=5)
1 => string 'blanc' (length=5)
'quantite' =>
array (size=2)
0 => int 6
1 => int '8'
My table has more field :
the 'ID' field, which need to auto increment.
the 'reference' field, which contains the reference of the order, I will generate it randomly.
The 'ARTCOD' field, it's the code associated to an article, here it's in $_SESSION['panier']['ARTCOD'].
The 'CLICOD' field, it's the code associated to the client which is ordering, here it's in $_SESSION['CLICOD'].
the 'quantite' field, the quantity of the ordered article, contained in $_SESSION['panier']['quantite'].
The 'type' field, contain the order type, here it's just a defined word that will not change.
And the 'date' field, contain the timestamp of the order.
So I need help to write a function that will generate my MySQL request without using multiple INSERT.
I've already create this:
$query = "";
for ($i = 0; $i < count($_SESSION['panier']['ARTCOD']); ++$i) {
$query .= 'INSERT INTO commandevalide (id, reference, ARTCOD, CLICOD, quantite, type, date) VALUES ("", "'.$_SESSION['panier']['ARTCOD']['$i'].'", "'.$reference.'", "'.$_SESSION['CLICOD'].'", '.$_SESSION['panier']['quantite']['$i'].', "Location", now());';
}
But I prefer something which will give just one INSERT request.
I saw that I need to use the implode function and a foreach loop but I did not manage to create something working.
To combine all those inserts into a single one, you can try this :
$query = "INSERT INTO commandevalide (id, reference, ARTCOD, CLICOD, quantite, type, date) VALUES ";
for ($i = 0; $i < count($_SESSION['panier']['ARTCOD']); ++$i) {
$query .= '("", "'.$_SESSION['panier']['ARTCOD'][$i].'", "'.$reference.'", "'.$_SESSION['CLICOD'].'", '.$_SESSION['panier']['quantite'][$i].', "Location", now()), ';
}
$query = rtrim($query, ', ');
Note : Don't put $i between single quotes.
Currently I'm looping through a quite large data set. This multidimensional array needs to be grouped by specific array values of its sub arrays. As this is a holiday project, I want to do deepen my knowledge and make more use of PHPs Iterators. Point is, that I don't know how to transform a numeric multi-dimensional Array into a multi-dimensional array with associative keys.
Shortened example (GeoJSON to Array)
array (size=4)
'type' => string 'FeatureCollection' (length=17)
'features' => // THIS is the actual array
array (size=207)
0 => // Sub-Arrays like this one are repeating
array (size=5)
'type' => string 'Feature' (length=7)
'geometry' =>
array (size=2)
'type' => string 'LineString' (length=10)
'coordinates' =>
array (size=410)
0 =>
array (size=2)
0 => float 16.359980888872
1 => float 48.208437070943
// etc.
'geometry_name' => string 'SHAPE' (length=5)
'properties' =>
array (size=5)
'OBJECTID' => int 273
// This/"LBEZEICHNUNG" is the part I want to order/summon
// all further "geometry"-parts by
'LBEZEICHNUNG' => string '13A, 2, 86, U3' (length=1)
'LTYP' => string '1' (length=1)
'LTYPTXT' => string 'Tramway' (length=12)
'SE_ANNO_CAD_DATA' => null
'id' => int 1
The features array is what holds the actually looped datasets. And LBEZEICHNUNG are the values (single or comma separated) I want to sort/order by.
To make an example:
// Original values:
'LBEZEICHNUNG' => string '13A, 2, 86, U3'
// Now split them and push the features into new keys that have those values:
'13A' => array(
0 => // Sub-Arrays like this one are repeating
array (size=5)
'type' => string 'Feature' (length=7)
'geometry' =>
array (size=2)
'type' => string 'LineString' (length=10)
'coordinates' =>
array (size=410)
0 =>
array (size=2)
0 => float 16.359980888872
1 => float 48.208437070943
// etc.
'geometry_name' => string 'SHAPE' (length=5)
'properties' =>
array (size=5)
// "OBJECTID" now is obsolete
// "LBEZEICHNUNG" is now obsolete
'LTYP' => string '1' (length=1)
'LTYPTXT' => string 'Tramway' (length=12)
'SE_ANNO_CAD_DATA' => null
// "id" now is obsolete as well
),
"2" => // gets the same values as "13A"
// same goes for "86" and "U3"
Now every sub array that would have either 13A, 2, 86 or U3 in ["properties"]["LBEZEICHNUNG"], would push its geometry to the end of the already existing subarray/sub-Iterator.
So far I only got a basic recursive Iterator set up, that runs through all leaves.
$data = new \RecursiveArrayIterator( $fileContents );
foreach( new \RecursiveIteratorIterator( $data ) as $key => $value )
{
// foo. bar. dragons.
}
Point is that I can't really figure out how to assign new keys from values in the Iterator. I already tried using a RecursiveFilterIterator and failed gracefully as its simply not intended to do this. Quite frankly: I'm lost as I either can't find the right Iterator to use or I simply ain't know enough about Iterators yet.
I got a working solution with nested foreach-es pushing into another Array. As this is my holiday project I want to learn, hence the Iterator solution, which I hope is more maintainable in the long turn.
Edit: Link to the original Geo-JSON data set CC-BY-SA 3.0/AUT - Data provided by the City of Vienna. Other formats can be found here.
If I understood correctly, you want to sort/ or group the array based on that "LBEZEICHNUNG" key, and use PHP iterators. In order to do that, you have to traverse the entire array, and build a new one that holds the values grouped by that key. This is simple foreach logic.
Iterators shine when you want to traverse a data collection and fetch the data during traversal (or alter it).
In this case, you are fetching the data outside of the iterator (json_decode ?), so that makes iterators kind of pointless - unless you need to do more than just sorting. If you do, I'd suggest you store that data in a format that allows you to easily fetch sorted sets, like a database, then you can use iterators to their full potential.
One way to group the routes is to use basic OOP:
class Route{
protected $trams = array();
// add other route properties (type, geometry etc.)
public function assignTo(Tram $line){
if(!in_array($line, $this->trams, true))
$this->trams[] = $line;
}
public function getTrams(){
return $this->trams;
}
}
class Tram{
public $name;
protected $routes = array();
public function __construct($name){
$this->name= $name;
}
public function addRoute(Route $route){
$this->routes[] = $route;
$route->assignTo($this);
}
public function getRoutes(){
return $this->routes;
}
}
Example:
$trams = array();
foreach($data as $routeData){
$route = new Route();
$tramNames = explode(', ', $routeData['features']['properties']['LBEZEICHNUNG']);
foreach($tramNames as $name){
if(!isset($trams[$name]))
$trams[$name] = new Tram($name);
$trams[$name]->addRoute($route);
// set other route properties...
}
}
You can use usort to sort your multi-dimensional array based on sub-values:
$JSON = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode(file_get_contents("http://data.wien.gv.at/daten/geoserver/ows?service=WFS&request=GetFeature&version=1.1.0&srsName=EPSG:4326&outputFormat=json&typeName=ogdwien:OEFFLINIENOGD")));
$geoarray = json_decode($JSON, true);
$myarray = $geoarray["features"];
function cmp($a, $b) {
return $a["properties"]["LBEZEICHNUNG"] - $b["properties"]["LBEZEICHNUNG"];
}
usort($myarray, "cmp");
print_r($myarray);
I have a form in which i use two dimensional array for field names.The fields names are below
myform[message][]
myform[name][]
myform[add][]
it means there are three arrays.Every array has arrays inside it.when i var_dump my form after putting values and submitting it.I get the below structure of 2d array.
array
''message'' =>
array
0 => string 'adnan' (length=5)
1 => string 'khan' (length=4)
2 => string 'salman' (length=6)
''name'' =>
array
0 => string 'khan' (length=4)
1 => string 'kamran' (length=6)
2 => string 'khan' (length=4)
''add'' =>
array
0 => string 'asad' (length=4)
1 => string 'khan' (length=4)
2 => string 'abrar' (length=5)
As you can see the associative array.I want to store the values of message,name and add in a database table having three fields to store the values of message,name and add fields in a single query by using some loop like foreach.
when i use this code
foreach($_REQUEST['myform'] as $val)
foreach($val as $v)
{
echo $v;
}
I get all the values of the array.But i think i am unable to save it to database table
as all the values are in the variable $v.How to store message in a message field,name in name field and add in an add field in a table of a db.
please advice.Thanks
The looping is the easy part.
if (isset($_REQUEST['myform']))
{
foreach($_REQUEST['myform'] as $key=>$value)
{
// DO SOMETHING
}
}
The hard part is knowing what you want to do. You say put it in a database but you don't give any real info about what or where. Just make sure you carefully escape any user input before storing it, or better yet use prepared queries.
I'm total newbie to PHP and Drupal but I fix this simple(?) thingo on my template. I want to get title, date, text and link path from this array? I can't get it out of there. I think its because its in inside of another array and because im noob in PHP I cant get it out of there ? Also I would like to get it to a loop. If theres more content, I would get it as a list or something. I would use foreach for this? Like foreach $contents as $content and so on?
I get this output from this: var_dump($contents);
array
'total' => string '1' (length=1)
'data' =>
array
0 =>
array
'cid' => string '13231' (length=3)
'title' => string 'TITLEBLABLABLA' (length=3)
'body_text' => string 'TEXTBLABLABAL' (length=709)
'created' => string '313131' (length=10)
'created' => string '2010-07-13 14:12:11' (length=19)
'path' => string 'http://goog.fi' (length=72)
Think of accessing multidimensional arrays in the same way you'd access a file in a subdirectory: just reference each level/directory in sequence. Assuming that array is stored in $arr, you'd get the title as follows:
$arr['data']['0']['title']
Here is a basic PHP array tutorial
It comes down to this:
You retrieve an element of an array with []
$array = array( 'a' => 'b');
echo $array['a']; //Prints b;
To loop through a multi-dimensional array and echo date try this...
foreach ($contents as $key => $content) {
echo $content[$key]['created'];
}
If that doesn't work, post the output of print_r($content) in your question so I can't build you exact array. I'm kinda confused over the structure of your array in your question.