Jump to content

Recommended Posts

Just to clarify, which part don't you understand? The $data object is an associative array, so you can access the colors using the respective key:

$colors = $page->meta('myData')['colors']; // ['red', 'green', 'blue']

The $colors array is an indexed / numerical array (i.e. it's not associativ), so you can access each of the colors using the numerical key of the position you want:

$colors = $page->meta('myData')['colors']; // ['red', 'green', 'blue']
echo $colors[0]; // red
echo $colors[2]; // blue

Or are you stuck on how to use the meta method itself?

  • Like 1

Share this post


Link to post
Share on other sites

@stanoliver Great 🙂 Array elements that are declared without a key are implicitly numeric in PHP, so the following declarations are equivalent:

$colors = [
	'red',
	'green',
	'blue',
];

$colors = [
	0 => 'red',
	1 => 'green',
	2 => 'blue',
];

You can even mix numerical and associative arrays, but that only leads to confusion in my opinion, so I would avoid it.

  • Like 2

Share this post


Link to post
Share on other sites

@MoritzLost and @szabes First thanks for your additions. Do you guys may have an elegant solution for a  related situation?

Let's asume I have 5 cars in an excel-like-spreadsheet.

Further I have a two rows in a datatable

car1     car2   car3   car4    car5

100      200    300   400     500      (Powerhorses/PS)

If I would like to export the data out of my example above to a csv-file the data in the csv-file may look like

"car1";"car2";"car3";"car4";"car5";

"100";"200";"300";"400";"500";

The syntax of the array declaration

$colors = [
	'red',
	'green',
	'blue',
];

and syntax of my spreadsheet data looks quite similiar. I would be even more similiar if my csv would look like:

'car1','car2','car3','car4','car5'

'100','200','300','400','500'

and therefore I could just copy-paste a raw of my csv-file so that I could become an array declaration like:

$price = [
	'100','200','300','400','500'
];

So the array declaration could be simple done by copy pasting out of my csv file.

Now to the problem: Are their ways to adjust the working syntax/code 

echo $carps[0];
echo $carps[1];
echo $carps[2];
echo $carps[3];
echo $carps[4];

by a loop or also without a loop so that the whole array gets output at once without repeating myself 4 more times.

Also it would be important that the adjusted code leaves a possibilty styling the output with some css.

 

Share this post


Link to post
Share on other sites
9 hours ago, stanoliver said:

Let's asume I have 5 cars in an excel-like-spreadsheet.

Further I have a two rows in a datatable

If you have 5 cars, then you'd have 5 rows of data (1 row = 1 record-set), not 2.

9 hours ago, stanoliver said:

so that the whole array gets output at once without repeating myself 4 more times

use a classic foreach loop or for debugging purposes print_r($cars)

Share this post


Link to post
Share on other sites

@dragan Probably you misunderstood me. 

The first row in my spreadsheet is just the names/titles of the cars:  'car1','car2',..., 'car5'

The second row will show the PS (Powerhorses) of my cars: '100','200','300','400','500'

So 5 columns and 1 row is totally fine.

A foreach loop with an icrement will work but is there no shorter/more comfortable way possible at least if my amount of cars (5 columns) will be fixed.

Something like in my own "pseudo-Code": 

echo $carps[0-4];

which would output the ps of the first car, then the ps of the second car and so on ...

Share this post


Link to post
Share on other sites

@stanoliver I don't quite understand your situation, but if you have some data in an array, you have a couple of methods to output it. A simple foreach loop will keep the code at the same length regardless of how many columns you need:

$prices = [
	'100', '200', '300', '400', '500'
];

foreach ($prices as $price) {
    echo $price . ' ';
}

// output:
// 100 200 300 400 500 
// note there's one final space after "500"

If you need to have something in between each item, for example a comma for CSV-style notation, you can use implode:

$prices = [
	'100', '200', '300', '400', '500'
];

echo implode(', ', $prices);

// output:
// 100, 200, 300, 400, 500

Finally, if you need to add something before or after each item or manipulate the items in some way, you can use array_map, which applies a callback function to each element of the array and returns a new array with the return values. For example, to wrap each element in double quotes for the CSV delimiters:

$prices = [
	'100', '200', '300', '400', '500'
];

echo implode(',', array_map(function ($price) {
	return '"' . $price . '"';
}, $prices));

// output:
// "100","200","300","400","500"

 

  • Like 1

Share this post


Link to post
Share on other sites

Hi @MoritzLost your provided examples just work great. Two little things I still have not found out yet:

1. In the backend I created a simple text field named "datarow". In my php-template I wanna use your example 

$prices = [
	'100', '200', '300', '400', '500'
];

foreach ($prices as $price) {
    echo $price . ' ';
}

which just works fine. How do I have to change the code of your example if I want everything between the [ ] to be my field "datarow"? How to change the foreach?

With repeating a lot of code I would do something like:
 

$prices = [ '100', '200', '300', '400', '500' ];  // 

$prices2 = [ '500', '400', '300', '4040', '5400' ];

Desired output would be something like (no comes pseudocode) on a normal processwire page:

foreach start

$prices = [ datarow ]; // datarow ist the created simple textfield which should be editable by an enduser

foreach end

I tried something like 

<?php
echo $prices=[<?= $page->datarow ?>] ;
?>

which could not work because nested php-code throws errors and the foreach is not even implemented.

Share this post


Link to post
Share on other sites

@stanoliver Assuming the text from your datarow field looks something like this:

100,200,300,400,500

You can use the explode function to split the string into an array using the commas as a delimiter. For example:

$prices = explode(',', $page->datarow); // ["100", "200", "300", "400", "500"]

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By EyeDentify
      I have been experimenting with the new $page->meta() method and find it useful.

      Once i figured out that the data i "save" with it is tied to the page where i called the method from.

      So this is not obvious at least not for me in the documentation:
      https://processwire.com/api/ref/page/meta/
       
      So i just wanted to share that revelation with the community so you don´t get as confused as i was.

      Happy Coding Everyone.
    • By VeiJari
      Hello forum. I'm trying to figure out how to detect if current form has errors after saving it in pw admin page. This is so that our event location isn't added in database if we detect errors. But I can't seem to find a correct way to detect errors? I only found the wire()->errors() and it always triggers even if I don't have any errors. 
      How can I detect errors in a form?
      By error I mean $page->error('this is the red error');
    • By VeiJari
      Hello forum!
      I've yet again stumbled on a head-scratching situation. We have enabled the option on our articles template and events template that it skips the title adding part and goes straight to the form. This is what our customer wants. So when you add a new article or event it automatically names it temporary to "article-0000000" and same with event. Now the problem is that obviously after saving the form we want to change to page url or "name" to the title, like it's normally. 
      Now here's the code for the hook:
      wire()->addHookBefore("Pages::saved(template=tapahtuma|artikkeli)", function($hook) {
        $page = $hook->arguments(0);
        $newUrl = wire()->sanitizer->pageName($page->title); // give it a name used in the url for the page
        wire()->log->message($page->name);
        $page->setAndSave('name', $newUrl);
      });
      I get the correct page and the name and path changes when I log them, but when I try to save it. It just loads and then I get: 
      Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) This happens in sanitizer.php
      and then another error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes) in Unknown on line 0
       
      What is happening? Am I not suppose to use sanitizer in this way? When we made a temporary page object in out other hook, the sanitizer worked perfectly.
      Thanks for the help!
    • By VeiJari
      Hello, our customer doesn't like the fact that they have to first add a title and then add the other info in the form. Therefore, we've enabled the way to skip this by making a temporary file before saving.
      But the problem is that by using module schedulepages in this piece of code in the module:  
      if (!$page->isNew() && $page->publishable() && $page->isChanged('status') && $page->is(Page::statusUnpublished) && $page->publish_from) {
                  $this->session->error($this->_("“Publish From Date” field was cleared to prevent the page from being unintentionally re-published on the next Lazy Cron run."));
                  $page->publish_from = null;
                  $page->save('publish_from');
              }
      it fires even with the temporary file and therefore after first save it resets the publish_from field. Is there a way to check if template is temporary, or something along those lines?
      One solution is just to ask the customer to first save the form after adding a title, but I don't see that as a good solution.
×
×
  • Create New...