How to modify output of certain function of File_CSV_DataSource? - php

The following function is from a PEAR script called File_CSV_DataSource, and is a CSV parser.
CSV file is this:
name,age,skill
john,13,knows magic
tanaka,8,makes sushi
jose,5,dances salsa
The current output of this function is like this:
array (0 => array ('name' => 'john','age' => '13','skill' => 'knows magic',),1 =>array('name' => 'tanaka','age' => '8','skill' => 'makes sushi',),2 =>array ('name' => 'jose','age' => '5','skill' => 'dances salsa',),)
what I'm trying to achieve is to make the function to output like this:
array (array ('john','13','knows magic'), array('tanaka','8','makes sushi'), array ( 'jose','5','dances salsa'),)
so without the 0 => and without the column header => , only the value of the cells
Is there any way for me to modify the function bellow to make it output as in my example above?
public function connect($columns = array())
{
if (!$this->isSymmetric()) {
return array();
}
if (!is_array($columns)) {
return array();
}
if ($columns === array()) {
$columns = $this->headers;
}
$ret_arr = array();
foreach ($this->rows as $record) {
$item_array = array();
foreach ($record as $column => $value) {
$header = $this->headers[$column];
if (in_array($header, $columns)) {
$item_array[$header] = $value;
}
}
// do not append empty results
if ($item_array !== array()) {
array_push($ret_arr, $item_array);
}
}
return $ret_arr;
}
Thanks in advance

Just use the built in filegetcsv. It will do that for you.

Related

Convert MySQL result to XML format using PHP with multidimensional array

I am trying to get my XML format be like this:
but my code now does not loop for the 'order_line' array and will return like this:
below are sample of my code I did:
$result = $this->db->query("SELECT * FROM `grn_order` a");
foreach($result->result() as $row )
{
$result_line = $this->db->query("SELECT * FROM `grn_order_line` a where a.order_no = '$row->order_no'");
foreach($result_line->result() as $row_line);
{
$line = array(
'guid' => $row_line->guid,
'itemcode' => $row_line->itemcode,
);
}
$my_array[] = array(
'order_no' => $row->order_no,
'loc_code' => $row->loc_code,
'trans_code' => $row->trans_code,
'po_no' => $row->po_no,
'order_line' => $line
);
} $xml = new SimpleXMLElement('<orders/>');
// function callback
$data = $this->array2XML($xml, $my_array);
print $xml->asXML();
function array2XML($obj, $array)
{
foreach ($array as $key => $value)
{
if(is_numeric($key))
$key = 'order';
if (is_array($value))
{
$node = $obj->addChild($key);
$this->array2XML($node, $value);
}
else
{
$obj->addChild($key, htmlspecialchars($value));
}
}
}
You keep on overwriting the last line in your load loop. Change it to...
$line = [];
foreach($result_line->result() as $row_line);
{
$line[] = array(
'guid' => $row_line->guid,
'itemcode' => $row_line->itemcode,
);
}
So each line is added using $line[].

php - how to convert 'tree-array' to array

I have gotten the tree-array like that:
Now I want to convert it to an array like this:
array(
1 => array('id'=>'1','parentid'=>0),
2 => array('id'=>'2','parentid'=>0),
3 => array('id'=>'3','parentid'=>1),
4 => array('id'=>'4','parentid'=>1),
5 => array('id'=>'5','parentid'=>2),
6 => array('id'=>'6','parentid'=>3),
7 => array('id'=>'7','parentid'=>3)
);
I had already coded something like this:
private function _getOrderData($datas)
{
$_data = [];
static $i = 0;
foreach ($datas as $data) {
$i++;
$rows = ['id' => $data['id'], 'pid' => isset($data['children']) ? $data['id'] : 0, 'menu_order' => $i];
if(isset($data['children'])) {
$this->_getOrderData($data['children']);
}
$_data[] = $rows;
}
return $_data;
}
But it didn't work
Cry~~
How can I fix my code to get the array? Thanks~
BTW, my English is pool.
So much as I don't know you can read my description of the problem or not.
I had already solved this problem, Thx~
private function _getOrderData($datas, $parentid = 0)
{
$array = [];
foreach ($datas as $val) {
$indata = array("id" => $val["id"], "parentid" => $parentid);
$array[] = $indata;
if (isset($val["children"])) {
$children = $this->_getOrderData($val["children"], $val["id"]);
if ($children) {
$array = array_merge($array, $children);
}
}
}
return $array;
}
The array look like:
array

Get Value Only From Multidemensional Code after a csv parse

I have been trying to get the value of my combined rate, but running into some trouble with simply getting the value :
Array ( [0] => Array ( [ZipCode] => 01014 [CombinedRate] => 0.0625 ) ) <--- this is the array that is printed.
Here is the full code:
<?php
function csv_to_array($filename= '', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$zipsearch = csv_to_array($_SERVER['DOCUMENT_ROOT'].'/textfiles/taxes.csv');
function search($array, $key, $value)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
$valueofzip = search( $zipsearch, 'ZipCode', '01014');
print_r($valueofzip)
/*
Need Code To print Just value of that array
*/
?>
I just need the value of the combined rate after the zipcode is found from the array that is printed, but for whatever reason I am just missing it,
How do I just get the value of "Combined Rate" from this array that is printed : Array ( [0] => Array ( [ZipCode] => 01014 [CombinedRate] => 0.0625 ) )
Essentially this page will print out a single tax rate
It looks like the value that you are trying to retrieve is simply:
$valueofzip[0]['CombinedRate']
i.e. the value with the key "CombinedRate" in the zeroth element of $valueofzip.
If you are anticipating there being more than one array returned by your search function, then a foreach loop would be more appropriate:
foreach($valueofzip as $zip) {
if (isset($zip['CombinedRate'])) echo $zip['CombinedRate'];
}
Depending on exactly what you want to do with the value, you might also want to take a look at array_walk, array_map, etc. in the documentation. They can be used to traverse the array and apply a callback function to each element. For example:
$valueofzip = array(array("ZipCode" => 01014, "CombinedRate" => 0.0625),
array("ZipCode" => 02025, "CombinedRate" => 0.125 ));
$combined_rates = array_map(function($x) { if (isset($x['CombinedRate'])) return $x['CombinedRate']; }, $valueofzip));
print_r($combined_rates);
Output:
Array
(
[0] => 0.0625
[1] => 0.125
)

How to remove the empty entity from an array

I have a function, which returns back the array. But the way I form this array is by "explode"ing a string. And when I do that, I get an extra empty string.
So now my issue is that I dont want to return the empty array entity.
My function code is shown below:
public function purge_file($keys)
{
if(empty($keys))
throw new C7_Exception('Missing/Bad arguments');
$lib_tools_storage = new C7_Lib_Tools_Storage();
$file_ids = explode(";",$keys);
foreach($file_ids as $key)
{
//echo "this is file_id = $key ";
if(!empty($key))
$lib_tools_storage->purge_file($key);
}
return array('result_code' => 0,
'data' => array('keys' => $file_ids)
);
}
You can trim the outer semicolons before passing to explode:
$keys = '1;2;3;4;';
$file_ids = explode(";", trim($keys, ';'));
print_r($file_ids);
/* output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
*/
public function purge_file($keys)
{
if(empty($keys))
throw new C7_Exception('Missing/Bad arguments');
$lib_tools_storage = new C7_Lib_Tools_Storage();
$file_ids = explode(";",$keys);
foreach($file_ids as $key)
{
//echo "this is file_id = $key ";
if(!empty($key))
$lib_tools_storage->purge_file($key);
}
foreach($file_ids as $key)
{
if (!empty($key))
{
$keys_new[] = $key;
}
}
return array('result_code' => 0,
'data' => array('keys' => $keys_new)
);
}
use this function array_filter(explode(",", $params['emails']));.

How to find an array from parent array?

I am using below code to find an array inside parent array but it is not working that is retuning empty even though the specified key exits in the parent array
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $cards_parent[$key];
break;
}
}
Do you know any array function that will search parent array for specified key and if found it will create an array starting from that key?
you want array_key_exists()
takes in a needle (string), then haystack (array) and returns true or false.
in one of the comments, there is a recursive solution that looks like it might be more like what you want. http://us2.php.net/manual/en/function.array-key-exists.php#94601
here you can use recursion:
function Recursor($arr)
{
if(is_array($arr))
{
foreach($arr as $k=>$v)
{
if($k == 'Cards')
{
$_GLOBAL['cards'][] = $card;
} else {
Recursor($arr[$k]);
}
}
}
}
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$_GLOBAL['cards'] = array();
Recursor($cards_parent);
Could you please put a print_r($feedData) up? I ran the below code
<?php
$feedData = array('BetradarLivescoreData' => array('Sport' => array('Category' => array('Tournament' => array('Match' => array('Cards' => array('hellow','jwalk')))))));
$cards_parent = $feedData['BetradarLivescoreData']['Sport']['Category']['Tournament']['Match'];
$cards = array();
foreach($cards_parent as $key => $card)
{
if ($key === 'Cards')
{
$cards[] = $card;
break;
}
}
print_r($cards);
And it returned a populated array:
Array ( [0] => Array ( [0] => hellow [1] => jwalk ) )
So your code is correct, it may be that your array $feedData is not.

Categories