ok below is my code
<?php
// Last 10 Jobs
function last10IT(){
$xml = simplexml_load_file('http://www.cv-library.co.uk/cgi-bin/feed.xml?affid=101899');
$new_array = array();
//$limit = 5;
//$c = 0;
foreach ($xml->jobs->job as $job) {
// if ($limit == $c) {
// break;
// }
$jobref = $job->jobref;
$title = $job->title;
$date = $job->date;
$new_array[$jobref.$date] = array(
'jobref' => $jobref,
'date' => $date,
'title' => $title,
'salary' => $job->salary,
'location' => $job->location,
);
}
}
ksort($new_array);
$showl = 10;
$n = 0;
foreach ($new_array as $date => $listing) {
print $listing['title'] . PHP_EOL;
}
?>
All I want it to do is filter by category & display a max of 10 results
for example
IT
so is there a way I can pass the category value into the function that I want it to filter by
instead of having to replicate for each category
All I get is :
Warning: ksort() expects parameter 1 to be array, null given in
C:\wamp\www\RECRUITMENTFAIR\functions.php on line 28
Please help guys
It something SO simple causing this error but its driving me mad because I just cannot see it
it is relative simple: you try to use the variable $new_array out of scope:
it is defined within your last10IT() function, but the function ends after the first foreach.
you should either return the array and call the function to get the array or move the part with the ksort and the printing into the function, depending on your needs.
Also was having issues by not having the PHP Extension xmlrpc enabled !
what a tool !
Thats why i was getting failed to open half the time
Related
I am having a bit of trouble trying to explain this correctly, so please bear with me...
I need to be able to recursively select keys based on a given array. I can do this via a fairly simple foreach statement (as shown below). However, I prefer to do things via PHP's built in functions whenever possible.
$selectors = array('plants', 'fruits', 'apple');
$list = array(
'plants' => array(
'fruits' => array(
'apple' => 'sweet',
'orange' => 'sweet',
'pear' => 'tart'
)
)
);
$select = $list;
foreach ($selectors as $selector) {
if (isset($select[$selector])) {
$select = $select[$selector];
} else {
exit("Error: '$selector' not found");
}
}
echo $select;
See this code in action
My Question: Is there a PHP function to recursively select array keys? If there is not, is there a better way than in the example above?
If i understand , you are searching about :
http://php.net/recursivearrayiterator
and
http://php.net/recursiveiteratoriterator
And code something like that:
$my_itera = new RecursiveIteratorIterator(new RecursiveArrayIterator($my_array));
$my_keys = array();
foreach ($my_itera as $my_key => $value) {
for ($i = $my_itera->getDepth() - 1; $i >= 0; $i--) {
$my_key = $my_itera->getSubIterator($i)->key() . '_' . $my_key;
}
$my_keys[] = $my_key;
}
var_export($my_keys);
I Hope it works.
I'm trying to filter an array (derived from a json object), so as to return the array key based on the value. I'm not sure if array search $key = array_search($value, $array); is the best way to do this (I can't make it work), and I think there must be a better way.
So far I've got this, but it isn't working. Grateful for any help!
public function getBedroomData(array $data,$num_beds = null,$type) {
$data = (array) $data;
if($num_beds > 0) {
$searchstring = "avg_".$num_beds."bed_property_".$type."_monthly";
} else {
$searchstring = "avg_property_".$type."_monthly";
}
$avg_string = array_search($data, $searchstring);
return $avg_string;
}
The array consists of average property prices taken from the nestoria api as follows:
http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json
This returns a long json object. My problem is that the data isn't consistent - and I'm looking for the quickest (run time) way to do the following:
$data['response']['metadata']['0'] //= data to return, [0] unknown
$data['response']['metadata']['0']['metadata_name'] = "avg_1bed_property_rent_monthly" //= string I know!
$data['response']['metadata']['1'] //= data to return, [1] unknown
$data['response']['metadata']['1']['metadata_name'] = "avg_1bed_property_buy_monthly" //= string I know!
$data['response']['metadata']['2'] = //= data to return, [2] unknown
$data['response']['metadata']['2']['metadata_name'] = "avg_2bed_property_buy_monthly" //= string I know!
.....
.....
.....
$data['response']['metadata']['10'] = avg_property_rent_monthly
$data['response']['metadata']['11'] = avg_property_buy_monthly
$data['response']['metadata'][most_recent_month] = the month reference for getting the data from each metadata list..
It isn't possible to filter the initial search query by number of bedrooms as far as I can work out. So, I've just been array slicing the output to get the information I've needed if bedrooms are selected, but as the data isn't consistent this often fails.
To search inside that particular json response from nestoria, a simple foreach loop can be used. First off, of course call the json data that you need. Then, extract the whole data, the the next step if pretty straightforward. Consider this example:
$url = 'http://api.nestoria.co.uk/api?country=uk&pretty=1&action=metadata&place_name=Clapham&price_type=fixed&encoding=json';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
$metadata = $data['response']['metadata'];
// dummy values
$num_beds = 1; // null or 0 or greater than 0
$type = 'buy'; // buy or rent
function getBedroomData($metadata, $num_beds = null, $type) {
$data = array();
$searchstring = (!$num_beds) ? "avg_property_".$type."_monthly" : "avg_".$num_beds."bed_property_".$type."_monthly";
$data['metadata_name'] = $searchstring;
$data['data'] = null;
foreach($metadata as $key => $value) {
if($value['metadata_name'] == $searchstring) {
$raw_data = $value['data']; // main data
// average price and data points
$avg_price = 0;
$data_points = 0;
foreach($raw_data as $index => $element) {
$avg_price += $element['avg_price'];
$data_points += $element['datapoints'];
}
$data_count = count($raw_data);
$price_average = $avg_price / $data_count;
$data_points_average = $data_points / $data_count;
$data['data'][] = array(
'average_price' => $price_average,
'average_datapoints' => $data_points_average,
'data' => $raw_data,
);
}
}
return $data;
}
$final = getBedroomData($metadata, $num_beds, $type);
print_r($final);
I am getting results from a mysql table and putting each cell into an array as follows:
$sqlArray = mysql_query("SELECT id,firstName FROM members WHERE id='$id'");
while ($arrayRow = mysql_fetch_array($sqlArray)) {
$friendArray[] = array(
'id' => $arrayRow['id'],
'firstName' => $arrayRow['firstName'],
);
}
Then I do a search for a specific friend. For example if I want to search for a friend name Osman, i would type and o and it will return to me all the results that start with the letter o. Here is my code for that:
function array_multi_search($array, $index, $pattern, $invert = FALSE) {
$output = array();
if (is_array($array)) {
foreach($array as $i => $arr) {
// The index must exist and match the pattern
if (isset($arr[$index]) && (bool) $invert !== (bool) preg_match($pattern, $arr[$index])) {
$output[$i] = $arr;
}
}
}
return $output;
}
$filtered = array_multi_search($friendArray, 'firstName', '/^o/i');
and then it will print out all the results. My problem is that it returned an error saying "Invalid argument supplied to foreach()" and that is why I added the if(is_array)) condition. It is working fine if I leave this code in the index.php page, but I moved it to a subfolder named phpScripts and it doesn't work there. Any Help?
$output is not returning any value because apparently $friendArray is not an array. But I verified that it is by using print_r($friendArray) and it returns all the member's id and firstName.
P.S. I use JavaScript to the the call using AJAX.
If your array structure is such:
$friendArray[] = array(
'id' => $arrayRow['id'],
'firstName' => $arrayRow['firstName'],
);
This means your array is indexed and two levels.
So the correct way to walk through it is:
foreach($array as $cur_element) {
$id = $cur_element['id'];
$firstName = $cur_element['firstName'];
}
Change this:
foreach($array as $i => $arr) {
To this:
foreach((array)$array as $i => $arr) {
Are you sure that $array is not empty?
I'm rather new to PHP and I am kind of stuck here writing this simple script; what I am trying to ultimately do is go through the content of a string and find the positions of all the occurrences I have listed in my $definitions array then map those positions in a separate array and return it...
rather simple but I am not sure where the problem arises, when i print_r on the array in different parts of code, thinking its a scope issue, I keep seeing that the key value of the array is NULL and also when I try and access a value of the array I am sure exists for a given key, i also get nothing; any help would be appreciated...
thank you!
<?php
class html2DokuWiki {
function definition_map($content){
$definitions = array("<title" => " ","<h" => array("=", 6),"<p" => "\n\n","<b" => "**","<strong" => "**","<em" => "//","<u" => "__","<img" => " ","<a" => " ","<ul" => " ","<ol" => "*","<li" => "-","<dl" => " ","<dt" => " ","<dd" => " ");
$element_pos = array();
foreach($definitions as $html_element){
$offset = 0;
$counter = 0;
$element_pos[(string)$html_element] = array(); //ask phil why do i need to cast in order to use the object?
while($offset = strpos($content, $html_element, $offset + 1)){
$element_pos[(string)$html_element][] = $offset;
};
};
//print_r($element_pos);
echo $element_pos["<p"][0];
return $element_pos;}
function run($page){
return $this->definition_map($page);}
};
$debug = new html2DokuWiki();
$url = "http://www.unixwiz.net/techtips/sql-injection.html";
$content = file_get_contents($url);
//echo $content;
//print_r($debug->run($content));
$test = $debug->run($content);
echo "<p> THIS:".$test["<p"][0]."</p>";
//print_r($test);
?>
If it's the key you want to use as $html_element as an index you should do:
foreach($definitions as $html_element => $value){
Here is example how my array should look like:
$library = array(
'book' => array(
array(
'authorFirst' => 'Mark',
'authorLast' => 'Twain',
'title' => 'The Innocents Abroad'
),
array(
'authorFirst' => 'Charles',
'authorLast' => 'Dickens',
'title' => 'Oliver Twist'
)
)
);
When I get results from oracle database:
$row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS);
But when I execute my code I only get one row.
For example: <books><book></book><name></name></books>
But I want all rows to be shown in xml.
EDIT:
This is my class for converting array to xml:
public static function toXml($data, $rootNodeName = 'data', &$xml=null)
{
// turn off compatibility mode as simple xml throws a wobbly if you don't.
if (ini_get('zend.ze1_compatibility_mode') == 1)
{
ini_set ('zend.ze1_compatibility_mode', 0);
}
if (is_null($xml))
{
$xml = simplexml_load_string("<".key($data)."/>");
}
// loop through the data passed in.
foreach($data as $key => $value)
{
// if numeric key, assume array of rootNodeName elements
if (is_numeric($key))
{
$key = $rootNodeName;
}
// delete any char not allowed in XML element names
$key = preg_replace('/[^a-z0-9\-\_\.\:]/i', '', $key);
// if there is another array found recrusively call this function
if (is_array($value))
{
// create a new node unless this is an array of elements
$node = ArrayToXML::isAssoc($value) ? $xml->addChild($key) : $xml;
// recrusive call - pass $key as the new rootNodeName
ArrayToXML::toXml($value, $key, $node);
}
else
{
// add single node.
$value = htmlentities($value);
$xml->addChild($key,$value);
}
}
// pass back as string. or simple xml object if you want!
return $xml->asXML();
}
// determine if a variable is an associative array
public static function isAssoc( $array ) {
return (is_array($array) && 0 !== count(array_diff_key($array, array_keys(array_keys($array)))));
}
}
?>
Now with below responde I have tried problem is I get following output: <book>...</book> tags after each row.. then I tried 3 dimensional array now I get: <book><book>...</book></book> on the proper place but I have 2 of them.
This is the line where I have determine which is root on that array and that's why I get this output. But don't know how to change it : $xml = simplexml_load_string("<".key($data)."/>");
Thank you.
oci_fetch_array() will always return a single row, you need to call it until there are no more rows to fetch in order to get all of them:
while ($row = oci_fetch_array($refcur, OCI_ASSOC+OCI_RETURN_NULLS))
{
$library['book'][] = $row;
}