I have array output like below,
Array ( [0] => Array ( [file_name] => test.pdf
[file_type] => application/pdf
[file_path] => /Applications/AMPPS/www/testing/uploads/attachments/2/
[1] => Array ( [file_name] => test1.pdf
[file_type] => application/pdf
[file_path] => /Applications/AMPPS/www/testing/uploads/attachments/2/ )
How can i pull a new array like below
Array( [0] => test.pdf [1] => test1.pdf)
Background,
I am doing multiple file upload using Codeigniter, my files are uploading and getting return data array, i want only file names to be send back to my view, so need to pull file names of files which are uploaded,
Any suggestions, hints?
Thanks,
Use array_column() like,
$new_array = array_column ($your_array, 'file_name');
If using PHP version < 5.5, refer this
<?php
$arrResult = array();
foreach ($arrGiven as $key => $value) {
$arrResult[] = $value['file_name'];
}
$arrGiven is the first array from which you want to extract the data. $arrResult will contain the data like you wanted.
$new = array();
foreach($old as $entrie){
$new[] = $entrie['file_name'];
}
This will go through all the entreis of the old array, and put the file_name of each in a new array.
Simply do this
$files = array();
foreach ($array as $key => $value) {
$files[] = $array[$key]['file_name'];
}
print_r($files);
Related
Thank you for the response. I will give it a try and update my question, I have my own code but it is a bit messy to show all. My problem is that I do not get the indexes right.
I use:
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $key => $value)
{
$products[$key] = str_getcsv($value);
}
And I manage to read the data, but this will give me an error:
if ((int)$products[$_sku] > 0 && isset($products[$_sku])) {
Error: Notice: Undefined index: test-product-1 in....
The 'test-product-1' is from the sku column in the csv file
Output from
echo '<pre>';
print_r($products);
echo '</pre>';
gives:
Array
(
[0] => Array
(
[0] => sku
[1] => qty
)
[1] => Array
(
[0] => test-product-1
[1] => 3
)
[2] => Array
(
[0] => test-product-2
[1] => 6
)
[3] => Array
(
[0] => test-product-3
[1] => 30
)
)
I am trying to use a csv file to be imported into the array to replace
$products = [
'test-product-1' => 3,
'test-product-2' => 6,
'test-product-3' => 30
];
But I can not produce the same array when I import from the CSV file, which will cause problems. Examples for CSV to array: http://php.net/manual/en/function.str-getcsv.php
CSV file:
sku,qty
test-product-1,3
test-product-2,6
test-product-3,30
Next step is to extend the script to handle prices. I need to be able to pick up these variables from the CSV file too. And use them inside the for loop.
sku,qty,price,special_price
test-product-1,3,100,50
test-product-2,6,99,
test-product-3,30,500,300
I think the problem is that when you store the row, your storing it indexed by the row number ($key will be the line number in the file). Instead I think you want to index it by the first column of the CSV file. So extract the data first (using str_getcsv() as you do already) and index by the first column ([0])...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
foreach ($lines as $value)
{
$data = str_getcsv($value);
$products[$data[0]] = $data;
}
If you want to add the first row as a header and use it to key the data...
$products = array();
$lines = file('data_stock.csv', FILE_IGNORE_NEW_LINES);
$headers = str_getcsv(array_shift($lines));
$products = array();
foreach ( $lines as $value ) {
$data = str_getcsv($value);
$products[$data[0]] = array_combine($headers, $data);
}
The removes the first row of the array using array_shift() and then uses this row in the array_combine() as the keys for each row. With your test data, you would get something like...
Array
(
[test-product-1] => Array
(
[sku] => test-product-1
[qty] => 3
[price] => 100
[special_price] => 50
)
I used following code in my project and its working fine for me.
I used csv_reader PHP library for it.
You have to put this library in your library folder and import it into file where you want to read your csv.
include_once('../csv_reader.php');
$read = new CSV_Reader;
$read->strFilePath = "file_name_with_path";
$read->strOutPutMode = 0; // 1 will show as HTML 0 will return an array
$read->setDefaultConfiguration();
$read->readTheCsv();
$dataArr = array();
$dataArr = $read->arrOutPut;
In $dataArr, i will get the result,
I have a PHP Multidimensional associative array structured in this way:
Array
(
[0] => Array
(
[serverid] => 1
[ip] => localhost
[name] => Server1
)
[1] => Array
(
[serverid] => 2
[ip] => localhost
[name] => Server2
)
[2] => Array
(
[serverid] => 3
[ip] => localhost
[name] => Server3
)
Now I need to push at the end of every subArray this new field with this value:
['page_url'] = base_url('/server/id/') . $server['serverid'];
Where $server['serverid'] is the serverid field relative to every single subArray.
I've tried with this cycle but seems it doesn't work:
$result = $query->result_array();
foreach($result as $server) {
$server['page_url'] = base_url('/server/id/') . $server['id'];
}
Any suggestion would be really appreciated.
If you want to modify the subarray when iterating trough an array in a foreach, you have to pass the variable as a reference using &.
If you change your code to the one below, it should work as you'll be changing the original array item instead of a created copy.
foreach($result as &$server) {
$server['page_url'] = base_url('/server/id/') . $server['id'];
}
This creates a temporary copy of the subarray, which you're changing and then throwing away on the next iteration:
foreach ($result as $server) {
$server['page_url'] = base_url('/server/id/') . $server['id'];
}
You want to change the original array. Something like this:
foreach (array_keys($result) as $index) {
$result[$index]['page_url'] = base_url('/server/id/') . $result[$index]['id'];
}
If you know you haven't mucked with the indexes in $result you could also just do:
for ($index = 0; $index < count($result); $index++) {
I have a result of a query, which is the name of the image. I am storing the image names for every image Id in an array. Now, on the view page I am using foreach loop to display these images. The problem is I can't extract the elements(the name of the images) from this array.
My array is
Array ( [0] => Array ( [0] => Array ( [picture] => 5a3a13f237715637629.jpeg ) ) [1] => Array ( [0] => Array ( [picture] => 5a3b602654cfd527057.jpg ) ) )
I have used print_r and got this, now I want to extract only the 5a3a13f237715637629.jpeg values and display these using foreach loop on the view page. Any help is welcome.
The simplest way I can think of would be to json the array and then use regex to extract the filenames. You are then left with an array of filenames to loop through and display:
preg_match('/\w+.jpeg/', json_encode($array), $matches);
print_r($matches);
The benefits of doing it this way are that you don't need to know the structure of the array or go through embedded looping to find the values.
If you want do want the loop way; try this:
$array = array(
1 => array(
'picture' => '5a3a13f237715637629.jpeg'
),
2 => array(
'picture' => 'fnofweofweiofniewof.jpeg'
)
);
print_r(search_r($array, 'picture', $results));
function search_r($array, $key, &$results) {
if (!is_array($array)) {
return;
}
if (isset($array[$key])) {
$results[] = $array[$key];
}
foreach ($array as $subarray) {
search_r($subarray, $key, $results);
}
return $results;
}
That will result:
Array
(
[0] => 5a3a13f237715637629.jpeg
[1] => fnofweofweiofniewof.jpeg
)
PS. This is an adaption of this answer
I have an array $templates that looks like this:
Array
(
[0] => Array
(
[displayName] => First Template
[fileName] => path_to_first_template
)
[1] => Array
(
[displayName] => Second Template
[fileName] => path_to_second_template
)
[2] => Array
(
[displayName] => Third template
[fileName] => path_to_third_template
)
)
And I want to make it to look like this:
Array
(
[path_to_first_template] => First Template
[path_to_second_template] => Second Template
[path_to_third_template] => Third Template
)
That is, I want the fileName of the nested arrays to be the new array's key and displayName to be its value.
Is there a pretty way to do this without having to loop through the array. I had no luck searching, as I didn't know exactly what to search for.
Here's a classic foreach in action:
$result = array();
foreach($array as $row) {
$result[$row['fileName']] = $row['displayName'];
};
Here's a "clever" way to do it:
$result = array();
array_walk($array, function($row) use (&$result) {
$result[$row['fileName']] = $row['displayName'];
});
As you can see, the second approach is not really better than the first one. The only advantage is that theoretically you can pile upon the second form because it is a single expression, but in practice it's a long enough expression already so you wouldn't want to do that.
Loop in your array and make a new one:
$newArray = array();
foreach($array as $val){
$newArray[$val['fileName']] = $val['displayName'];
}
print_r($newArray);
$ret = array()
foreach ($templates as $template) {
$ret[$template["fileName"]] = $template["displayName"];
}
I have two arrays, one is generated by using explode() on a comma separated string and the other is generated from result_array() in Codeigniter.
The results when doing print_r are:
From explode():
Array
(
[0] => keyword
[1] => test
)
From database:
Array
(
[0] => Array
(
[name] => keyword
)
[1] => Array
(
[name] => test
)
)
I need them to match up so I can use array_diff(), what's the best way to get them to match? Is there something other than result_array() in CI to get a compatible array?
You could create a new array like this:
foreach($fromDatabase as $x)
{
$arr[] = $x['name'];
}
Now, you will have two one dim arrays and you can run array_dif.
$new_array = array();
foreach ($array1 as $line) {
$new_array[] = array('name' => $line);
}
print_r($new_array);
That should work for you.