Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am a beginner in PHP and I have a large amount of data in a multidimensional array
$result =
array
(
array(
array("name" => "Volvo", "price" => 2222, "model" =>18),
array("name" => "Tata", "price" => 2222, "model" =>18),
array("name" => "Asoka", "price" => 2222, "model" =>18),
),
array(
array("name" => "BMW", "price" => 2222, "model" =>17),
array("name" => "Benz", "price" => 2222, "model" =>17),
array("name" => "Maroti", "price" => 2222, "model" =>17),
),
array(
array("name" => "porse", "price" => 25648, "model" =>16),
array("name" => "farari", "price" => 25486, "model" =>16),
array("name" => "Volvo", "price" => 25422, "model" =>16),
),
);
I iterate through the array with a foreach loop, and print the model row ways,
foreach($result as $k => $datas){
echo $datas[$k]['model'].'-->';
foreach($datas as $key => $data){
//print_r($data);
echo $data['price'] ;
echo $data['name'].'-*-';
}
echo '<br>';
}
and when I run this code, I receive the following output:
18-->2222Volvo-*-2222Tata-*-2222Asoka-*-
17-->2222BMW-*-2222Benz-*-2222Maroti-*-
16-->25648porse-*-25486farari-*-25422Volvo-*-
However, I am trying to print column ways this array in html table, in a similar fashion to below:
18 --> 17 --> 16-->
2222-Volvo 2222-BMW 25648-porse
2222-Tata 2222-Benz 25486-farari
2222Asoka 2222-Maroti 25422-Volvo
Try this :
<div style='display:flex; flex-direction: row; flex-wrap: wrap;'>
<?php
foreach($result as $k => $datas){
echo "<div style='display:flex; flex-direction: column;'>";
echo "<div>" . $datas[$k]['model'] . "--></div>";
foreach($datas as $key => $data){
//print_r($data);
echo "<div>" . $data['price'] . "-" . $data['name'] . "</div>" ;
}
echo '</div>';
}
?>
</div>
The output is :
As you can see, the logic is pure HTML/CSS :
First I wrap your data inside a flex container with direction as row and wrap so if you have a lot of element they will go in the next row.
Now in your foreach, each element are wrapped inside an other flex div but with the direction as column : so each new div inside this one will be display under the previous one.
All the div inside are simple div, now your turn to make some css to center text, add padding or whatever
Is it what you are looking hope ? If you have question about flexbox check this : https://css-tricks.com/snippets/css/a-guide-to-flexbox/
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 months ago.
Improve this question
I am trying to encode an associative array in php
$data = array(
"firstName" => $_POST["firstName"],
"lastName" => $_POST["lastName"],
"email" => $_POST["email"],
"telephone" => $_POST["telephone"]
);
however the output is in string format and not in array format.
string(98) "{"firstName":"rob","lastName":"shelford","email":"some#domain.co.uk","telephone":"01245454545"}"
The output needs to have the square brackets so the receiving server can read the data correctly.
Is there another syntax for the $data array I need to use?
EDIT 1
The offical PHP documentation https://www.php.net/manual/en/function.json-encode.php
states that
echo "Normal: ", json_encode($a), "\n";
can be used to output
Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
however when I try to use the "\n" flag, I receive an error
EDIT 2
The entire data I wish to convert
$data = array(
"applicants" => array(
"firstName" => $_POST["firstName"],
"lastName" => $_POST["lastName"],
"email" => $_POST["email"],
"telephone" => $_POST["telephone"]
),
"buyerType" => $_POST["buyerType"],
"organisationId" => "xxxxxxxxxx",
"introducerId" => "0",
"introducerBranchId" => "0",
"introducerNegotiatorId" => "0",
);
EDIT 3
I have made it work by passing this into json_encode() :
$data = array(
"applicants"=> [
array(
"email"=> $_POST["email"],
"firstName"=> $_POST["firstName"],
"lastName"=> $_POST["lastName"],
"telephone"=> $_POST["telephone"]
)
],
"buyerType" => $_POST["buyerType"],
"organisationId" => "xxxxxxxxxx",
);
I have also removed the unnecessary lines in the above example
EDIT 4
The actual output I was expecting, and actually got, after implementing EDIT3
string(138) "{"applicants":[{"email":"some#domain.co.uk","firstName":"rob","lastName":"test","telephone":"01200000000"}],"buyerType":"Purchase"}"
If you want nested array to be encoded with square brackets surrounded, just put it in an array in php.
$data['applicants'] = [$data['applicants']];
echo json_encode($data);
FYI indexed array [1,2] will be encoded to json list [1,2], and associative array ['x'=>1,'y'=>2] will be encoded to json object {"x":1,"y":1}.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have an array and I want to call the array by button, Also I wanted it keep calling the array every time when I click on button. Please correct the array if it has any issue.
my array is :
array (
"name" => __('name1','vbegy'),
"id" => $this->shortname."_menu_1",
"desc" => __('name2)','vbegy'),
"type" => "text",
"std" => __('name3','vbegy'),
),
array (
"name" => __('name4','vbegy'),
"id" => $this->shortname."_menu_1_url",
"desc" => __('name5)','vbegy'),
"type" => "text",
),
I think first thing you should do is to learn how to use HTML forms/buttons and use PHP to process them. Below is a simple form example.
In your HTML file, add
<form method="post" action="your-php-file.php">
<input type="text" name="text-name" value="">
<input type="submit" name="button-name" value="Submit">
</form>
In your PHP file (your-php-file.php), add
$array1 = array(
"name" => array('name1' => 'vbegy'),
"id" => $this->shortname."_menu_1",
"desc" => array('name2' => 'vbegy'),
"type" => "text",
"std" => array('name3','vbegy')
);
$array2 = array (
"name" => array('name4' => 'vbegy'),
"id" => $this->shortname."_menu_1_url",
"desc" => array('name5' => 'vbegy'),
"type" => "text"
);
if (isset($_POST['button-name'])) {
//use php to process your array data as you want
echo $array1['name']['name1']; //print vbegy
echo $array1['type']; //print text
echo $array2['desc']['name5']; //print vbegy
$std = $array1['std']['name3'];
echo $std; //print vbegy
echo "You clicked submit button!";
}
For detailed explanation, please use following links.
http://www.w3schools.com/php/php_forms.asp
http://www.w3schools.com/php/php_form_complete.asp
Hope this will help.
To describe my question a little more in detail, can I use variables (i.e. $player1) at the second level of my multidimentional array?
If so, how do I echo $player1["name"] and $player1["age"]?
Is it a better practice to use keys in multidimensional arrays (i.e. "player1" => array();) or variables (i.e. $player1 = array();)?
I am very new to php so your answers are very appreciated. Here is my code:
<?php
// list of players
$currentPlayers = array(
$player1 = array(
"name" => "Ryan",
"age" => 26,
"weight" => 200,
),
);
echo $currentPlayers[$player1]["name"];
echo "<br>";
echo $currentPlayers[$player1]["weight"];
First you are missing => after $player1 in your original array.
Second you are not setting value for your variable $player1,
<?php
$player1="value1";//declaring the value for $player1 variable
$currentPlayers = array(
$player1 => array(//replacing = to =>
"name" => "Ryan",
"age" => 26,
"weight" => 200,
),
);
echo $currentPlayers[$player1]["name"];
echo "<br>";
echo $currentPlayers[$player1]["weight"];
Output will be
Ryan
200
Explanation
Lets say you have to player one is ryan second is arif. Both ages and wieght are different. and lets say you have form to get the info.
For example if you enter arif. it will onlcy show information about arif. and if you enter ryan it will oncly show info for ryan.
<form action="" method="POST">
<input type="text" name="player">
<input type="submit" name="submit">
</form>
<?php
$currentPlayers = array(
"ryan" => array(//replacing = to =>
"name" => "Ryan",
"age" => 26,
"weight" => 200,
),
"arif" => array(//replacing = to =>
"name" => "arif",
"age" => 16,
"weight" => 100,
),
);
$player1=$_POST['player'];//Declaring the value for player1
echo $currentPlayers[$player1]["name"];
echo "<br>";
echo $currentPlayers[$player1]["weight"];
What you want is:
$currentPlayers = array(
"player1" => array(
"name" => "Ryan",
"age" => 26,
"weight" => 200,
),
);
$thisPlayer="player1";
echo $currentPlayers[$thisplayer]["name"];
PHP is very flexible.
A Variable can represent any type of data. A variable is some text that starts with a $. $myvariable
Strings are represented by some text within quotes. "this-is-a-string". Numbers have no quotes. 98.
Associative arrays use "keys" to organize data in the array. The keys can be strings (or numbers).
$value = "some value";
$key = 'key2';
$myarray = array("key1"=>$value, $key2=>"Some other value");
You can use variables to define either a key or a value when creating an array.
A multidimentional array is simply an array that contains another array.
$key = array("second_level_key"=>"Second level value");
$myarray = array("key1"=>$key);
Or
$array = array(0=>"somevalue", 1=>array("key"=>"value"));
Multidimensional arrays can go as deep as you care to make them, and you can use variables at any depth.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to define a two dimension array like below:
[40.1][John]
[40.2][Jane]
[40.7][Mary]
[40.10][Sara]
in other words I want to define an array with custom key. Later I need to access to the array values with the custom key. for instance :
echo(myarray[40.2]);
And I need to generate the array dynamically from XML , since the values are coming from a XML file.
The XML file which I want to generate the array from is like below:
<rules>
<rule>
<id>40.1</id>
<regex><![CDATA[/(?:\)\s*when\s*\d+\s*then)/]]></regex>
</rule>
<rule>
<id>40.2</id>
<regex><![CDATA[/(?:"\s*(?:#|--|{))/]]></regex>
</rule>
How should I create the array with above characteristics?
You can do this very easily by creating an associative array
$myarray = array(
"40.1" => "John",
"40.2" => "Jane",
"40.7" => "Mary",
"40.10" => "Sara"
);
Later on you can iterate over this array with a foreach loop
foreach($myarray as $key => $value) {
echo "<p>" . $key . " = " . $value . "</p>";
}
This will output to the screen
40.1 = John
40.2 = Jane
40.7 = Mary
40.10 = Sara
To create a new array and add items to is as easy as doing this
$myarray = array();
$myarray[$newkey] = $newvalue;
For a two dimensional array, you can define them like this
$myarray = array();
$myarray[$key] = array();
$myarray[$key]['John'] = 'some value';
$myarray[$key]['Jane'] = 'another value';
$myarray[$key2] = array();
$myarray[$key2]['Mary']= 'yet another value';
Or as a short cut
$myarray = array(
$key => array(
'John' => 'some value',
'Jane' => 'another value',
),
$key2 = array(
'Mary' => 'yet another value'
)
);
You can do it with associative array key => value.
$arr = array('40.1' => 'John', '40.2' => 'Jane', '40.7' => 'Mary', ...);
echo $arr['40.1']; // will return John
If you think to extend the data in the feature, you can do it with nested arrays
$arr = array(
'40.1' => array('name' => 'John', 'eyes' => 'green');
'40.2' => array('name' => 'Jane', 'eyes' => 'blue');
);
You can access nested array like this:
echo $arr['40.2']['eyes'] // return blue
You can see also PHP documentation about arrays here
Array keys
Notice! Do not use "float" as type for array keys.
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
Output will be:
array(1) {
[1]=>
string(1) "d"
}
Taken from http://www.php.net/manual/en/language.types.array.php.
Two-dimensional arrays
You can create your array like this:
$data = [
'40.2' => [
'John' => [
// and now this is second dimension
]
]
];
Add aditional stuff:
$data['40.2']['John'][] = ; // just append value
// or
$data['40.2']['John']['sex'] = 'Male'; // store it with key
Or if you need to store scalar values, you can define array like this:
$data = [
'40.2' => [
'John' => 'male' // storing scalar values
]
];
Sorry, If I misunderstood your question.
I have a variable number of multidimensional arrays but all with the same 4 possible values for each item.
For example:
Array
(
[companyid] => 1
[employeeid] => 1
[role] => "Something"
[name] => "Something"
)
but every array may have a different ammount of items inside it.
I want to turn all the arrays into one single table with lots of rows. I tried array_merge() but I end up with a table with 8, 12, 16... columns instead of more rows.
So... any ideas?
Thanks
Didn't test it, but you could try the following:
$table = array();
$columns = array('companyid' => '', 'employeeid' => '', 'role' => '', 'name' => '');
foreach($array as $item) {
$table[] = array_merge($columns, $item);
}
This should work since the documentation about array_merge say:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
So you either get the value of the current item or a default value that you can specify in the $columns array.
$array1=Array
(
"companyid" => 1,
"employeeid" => 4,
"role" => "Something",
"name" => "Something",
);
$array2=Array
(
"companyid" => array(2,2,2),
"employeeid" => 5,
"role" => "Something2",
"name" => "Something2"
);
$array3=Array
(
"companyid" => 3,
"employeeid" => 6,
"role" => "Something3",
"name" => "Something3"
);
//Using array_merge
$main_array["companyid"]=array_merge((array)$array1["companyid"],(array)$array2["companyid"],(array)$array3["companyid"]);
$main_array["employeeid"]=array_merge((array)$array1["employeeid"],(array)$array2["employeeid"],(array)$array3["employeeid"]);
for($i=0;$i<count($main_array["companyid"]);$i++)
echo $main_array["companyid"][$i] + "<br />";
for($i=0;$i<count($main_array["employeeid"]);$i++)
echo $main_array["employeeid"][$i] + "<br />";
I've tested the code above and seems right.
You coult also improve this code into a DRY function.