How to foreach this kind of array using php - php

array(1) {
["album_name"]=>
string(12) "Cover Photos"
}
array(1) {
["cover"]=>
string(111) "url"
}
array(1) {
["album_name"]=>
string(24) "Fun in Your Name! Photos"
}
array(1) {
["cover"]=>
string(108) "url"
}
This is what it return when I do a var_dumpto my variable, I tried a normal foreach:
<?php
foreach ($fb_albums as $my_albumsdata):
echo $my_albumsdata['cover'];
endforeach;
?>
But doesn't work...

Try this:
for($i=0; $i < count($yourArray); $i += 2) {
$name = $yourArray[$i]["album_name"]
$cover = $yourArray[$i+1]["cover"]
}
But, I think you must change the organisation of the Array.

assuming that you have an array of those four arrays....
the problem would seem to be that not every $my_albumsdata contains a "cover".
if(array_key_exists("cover", $my_albumsdata)) echo $my_albumsdata["cover"];
^should be a quick fix, but lacking context, I'm not sure if this works for you.

Related

Iterating through rangeToArray() in PhpSpreadsheet

I have Excel sheets that I need to perform calculations with.
I am using PHPSpreadsheet to read and write, as PHPExcel is now deprecated.
The problem I am experiencing is in getting values from a specific column to perform calculations.
After going through the documentation, I found that I can use the rangeToArray() function to retrieve the values.
My code looks like this:
$inputFiletype = 'Xlsx';
$inputFileName = './helloworld.xlsx';
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($inputFileName);
$find_val = $spreadsheet->getActiveSheet()->rangeToArray('K1:K5');
This, according to the documentation, creates an array ($find_vals).
However, when I attempt to loop through the array to view the values, I get an 'Array to string Conversion' notice, with the output of "Array".
If I use var_dump, I get the following:
array(5) { [0]=> array(1) { [0]=> float(1) } [1]=> array(1) { [0]=> float(2) } [2]=> array(1) { [0]=> float(3) } [3]=> array(1) { [0]=> float(4) } [4]=> array(1) { [0]=> float(5) } }
I have tried the following loop codes:
for($i=0; $i<=4; $i++) {
echo (string)$find_val[$i];
}
as well as
foreach($find_val as $vals) {
echo $vals;
}
I have also tried the following which changed the result a little:
for($i=0; $i<=4; $i++) {
echo (string)$find_val[$i][$i];
}
This output one value, and gave me Undefined Offset errors for the other 4 iterations.
How would I be able to successfully iterate through a rangeToArray value using the PhpSpreadsheet API?
Thanks in advance.
Similar answer here
foreach ($find_val as $cell) {
foreach ($cell as $finalValue) {
echo $finalValue . "\r\n";
}
}
Just saw your post now. Have you tried this?
You are almost there.
foreach($sheetData as $vals) {
echo $vals[0];
}

Advanced PHP loop

I get translations from database and want to get generate it in Javascript object, like:
var Lang = {
eng: {
txtUserName: 'Username',
txtLogout: 'Logout'
},
dnk: {
txtUserName: 'Brugernavn',
txtLogout: 'Afslut'
}
}
I got stuck in loops, the result I get is not what I need.
This is my PHP:
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) :
echo $allLang->lang_code . ': ';
echo '{';
foreach ( $translationsall as $translation ) :
if ( $translation['it_text'] == 'txtUserName' ) :
for ( $i = 1; $i <= 1; $i++ ){
var_dump($translationsall[$i]);
}
endif;
endforeach;
echo '},';
echo "\r\n";
endforeach;
?>
}
And this is what I get:
var Lang = {
dnk: {array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
},
eng: {array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "VMS"
}
}
How can I edit my loops to get result I need?
Maybe there is a smarter way to generate Lang object?
And, forgot to mention that I need only few translations, that's why I have this in PHP if:
if ( $translation['it_text'] == 'txtUserName' ) :
//stuff
endif;
Any ideas are welcome :)
And this what I get from var_dump($translationsall):
array(2748) {
[0]=>
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "CMS"
}
[1]=>
array(2) {
["it_text"]=>
string(8) "appTitle"
["it_name"]=>
string(3) "CMS"
}
[2]=>
array(2) {
["it_text"]=>
string(9) "txtLogout"
["it_name"]=>
string(6) "Afslut"
}
[3]=>
array(2) {
["it_text"]=>
string(9) "txtLogout"
["it_name"]=>
string(6) "Logout"
}
[4]=>
array(2) {
["it_text"]=>
string(10) "btnRefresh"
["it_name"]=>
string(9) "Hent Igen"
}
[5]=>
array(2) {
["it_text"]=>
string(10) "btnRefresh"
["it_name"]=>
string(7) "Refresh"
}
}
Please, don't do this. - Make an API call to a PHP backend producing the data you need. - Using either out of the box functions such as $.ajax from jQuery or other prebuilt frameworks will help you achieve this.
If you still want to go down the line of dynamically doing this (your question) - remove var_dump - which is ultimately dumping the type and other details (as it should) and use foreach (key, value) which will help you generate what you need. - But rather going down this dodgy route I'd recommend you take a look at how to serve an API using Laravel or other frameworks.
You could pass data from PHP to JS with JSON.
From PHP, you can use json_encode():
echo json_encode($translation);
And in your JS use JSON.parse():
var obj = JSON.parse('{"key":value}');
You can then do:
<?php
$allLangs = $this->params->getLanguages;
$json = json_encode($allLangs);
?>
<script>
var Lang = JSON.parse('<?php echo $json; ?>');
</script>
As others here have already mentioned; it is a bad idea to dynamically create your javascript like this - I would instead use JSON to serialize and deserialize the data. Anyway, if you insist on dynamic creation; it'll probably be something along the lines of;
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) {
echo $allLang->lang_code . ': {';
foreach ( $translationsall as $translation ) {
$total_words_to_translate = count($translation);
for($i = 0; i <= $total_words_to_translate; $i++){
if ( $translation['it_text'] == 'txtUserName' ){
print("txtUserName: ".$translationsall[$i]);
}
if ( $translation['it_text'] == 'txtLogout' ){
print("txtLogout: ".$translationsall[$i]);
}
}
}
echo '},';
echo "\r\n";
}
?> }
Its somewhat hard to determine the exact code when we don't know the structure / naming conventions of your database / variables.
Use json_encode:
var Lang = <?php
$all_langs = $this->params->getLanguages();
echo json_encode($all_langs);
?>;
Not sure how close I am with the data definitions, but I've included them so you can see what I'm assuming and hopefully be able to adjust it to your needs.
The way it works is that it starts at the beginning of $translationsall array and assumes that the $allLangs array is in the same order as the entries ( so in this case the dnk and then the eng values). These it then populates into the output under the language key, with it_text as the key and it_name as the translation.
$translationsall = [["it_text" => "txtLogout", "it_name"=>"Afslut"],
["it_text"=> "txtLogout", "it_name"=> "Logout"],
["it_text" => "txtLogout2", "it_name"=>"Afslut2"],
["it_text"=> "txtLogout2", "it_name"=> "Logout2"]
];
$allLangs = [ (object)["lang_code"=> "dnk"], (object)["lang_code"=> "eng"] ];
$countTrans = count($translationsall);
$out = [];
$i = 0;
while( $i < $countTrans ) {
foreach ( $allLangs as $language ) {
$out[$language->lang_code][$translationsall[$i]["it_text"]] = $translationsall[$i]["it_name"];
$i++;
}
}
echo json_encode($out, JSON_PRETTY_PRINT);
This prints out
{
"dnk": {
"txtLogout": "Afslut",
"txtLogout2": "Afslut2"
},
"eng": {
"txtLogout": "Logout",
"txtLogout2": "Logout2"
}
}
You can try with echo see bellow code :
var Lang = {
<?php
$allLangs = $this->params->getLanguages;
foreach ($allLangs as $allLang) :
echo $allLang->lang_code . ': ';
echo '{';
foreach ( $translationsall as $translation ) :
if ( $translation['it_text'] == 'txtUserName' and $translation['itl_lang_code '] == $allLang->lang_code) :
echo "txtUserName:'".$translation['it_text']."',txtLogout:'".$translation['it_name']."' ";
endif;
endforeach;
echo '}';
echo '},';
echo "\r\n";
endforeach;
?>
}

Combine varied number of dynamically named arrays

I have seen the following: array_merge() How can I add a 'range' of an array name and the answers don't work for me.
I have an array that I am looping through in order to slice and convert certain currency strings to float numbers. I then have to array_merge them back together in order to work with the array and have been dynamically naming them so that I don't overwrite the previous array_merge. After doing so, I then need to combine all of the dynamically named arrays into one array.
Initially I had the following code, which worked great when I only had 3 nested arrays in the $order['product'] array. However, this number varies, and the code needs to do so as well.
$nr = 1;
foreach ($order['product'] as $product) {
$product_total = array_slice($product, 1);
array_walk($product_total, "convertCurrencyStringtoNumber");
${"final_product" . $nr} = array_merge($product, $product_total);
$nr++;
};
$arrays = array($final_product1, $final_product2, $final_product3);
var_dump($arrays);
This results in the following array:
array(3) {
[0]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(18) }
[1]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(17) }
[2]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(2.75) } }
How do I implement a varied number of dynamically named arrays in the line:
$arrays = array($final_product1, $final_product2, $final_product3);
I attempted the following, but the array is nested incorrectly. Feel free to fix this code or come up with a better solution.
$nr = 1;
$i = 1;
foreach ($order['product'] as $product) {
$product_total = array_slice($product, 1);
array_walk($product_total, "convertCurrencyStringtoNumber");
${"final_product" . $nr} = array_merge($product, $product_total);
if ($nr > 0) {
$arrays = $final_product1;
for ($i = 2; $i <= $nr; $i++) {
$arrays = array_merge($arrays, ${"final_product" . $nr});
}
} else {
echo "There are no products in this order";
}
$nr++;
};
var_dump($arrays);
This results in the incorrectly nested array:
array(2) {
[0]=> array(2) {
[0]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(18) }
[1]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(17) } }
[1]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(2.75) } }
Simply replace your dynamically single-named variables with an array:
$final_product = array();
foreach ($order['product'] as $product) {
$product_total = array_slice($product, 1);
array_walk($product_total, "convertCurrencyStringtoNumber");
$final_product[] = array_merge($product, $product_total);
};
var_dump($final_product);
Unless I'm missing something here... this should be as easy and simple as:
$final_array=[];
foreach ($order['product'] as $product) {
$final_array[]['total'] = (float) $product['whatever value 1 is...'];
$final_array[]['source_code'] = $product['source_code'];
}
var_dump($final_array);
If you need to apply convertCurrencyStringtoNumberbecause it does something weird to the variable then changethe seccond line to:
$final_array[]['total'] = convertCurrencyStringtoNumber(array_slice($product, 1));

if inside for each loop pushing multidimensional array - php

I'm running two for each loops and pushing one of them into the other one. This works fine, except if my I have more than one match. In that case, I'm only getting the last one. Sorry about the title, not too sure how to call this question in one line.
foreach($items as &$item) {
foreach($fruits as &$fruit) {
$i = 0;
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
First array :
array(114) {
[0]=>
array(5) {
["id"]=>
string(2) "76"
...
}
...
}
Second array :
array(47) {
[0]=>
array(5) {
["id"]=>
string(1) "4"
["for"]=>
string(2) "76"
...
}
...
}
With multiple matches of the if($fruit['for']==$item['id']) logic, I'd like the following output.
array(114) {
[0]=>
array(6) {
["id"]=>
string(2) "76"
...
["fruits"]=>
array(2) {
[0]=>
array(5) {
["id"]=>
string(1) "4"
["for"]=>
string(2) "76"
...
}
[1]=>
array(5) {
["id"]=>
string(2) "33"
["for"]=>
string(2) "76"
...
}
}
}
}
What am I doing wrong?
take $i outside the loop, your match is always stored in $item["fruits"][0]
foreach($items as &$item) {
$i = 0;
foreach($fruits as &$fruit) {
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
You set $i to 0 for every array-element you check. This renders the $i++ useless and your first match gets overwritten. Try either this:
foreach($items as &$item) {
$i = 0;
foreach($fruits as &$fruit) {
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
or this: (depending on what exactly you will need)
$i = 0;
foreach($items as &$item) {
foreach($fruits as &$fruit) {
if($fruit['for']==$item['id']) {
$item["fruits"][$i] = $fruit;
$i++;
}
}
}
That way, each time you find a new match it gets a new key.

Add To Array Value

this must be very simple but I couldn't make it work.. PHP noob :P
I have this array "$e_cats" and when I do var_dump($e_cats); the result is this:
array(3) { [0]=> string(3) "192" [1]=> string(3) "190" [2]=> string(3) "191" }
What I want is to add "-" to every value inside, so "-192", "-190", and "-191". Here is my code:
foreach ($e_cats as $cat) {
$cat = '-' .$cat;
}
but when I do print_r($cat) the result is: -191 (not all values). What did I do wrong?
Thanks in advance
foreach($e_cats as $i => $cat) {
$e_cats[$i] = '-' . $cat;
}
You were close!

Categories