I am learning PHP and I got stuck on this part.
I need to create Array and go trough It with For loop but I got stuck. I either get Array to String conversion error or blank page.
$array = array(
array(1, "FirstName1", "LastName1", "email1#gmail.com"),
array(2, "FirstName2", "LastName2", "email2#gmail.com"),
array(3, "FirstName3", "LastName3", "email3#gmail.com"),
);
This is how my array needs to look. In what way I can use for loop to go trough it?
Also what is good way to go trough multidimensional array with string indexes like this?
$array = array(
array("ID" => 1,"fname" => "name","lname" => "name","email" => "mail#gmail.com"),
array("ID" => 2,"fname" => "name","lname" => "name","email" => "mail#gmail.com"),
array("ID" => 3,"fname" => "name","lname" => "name","email" => "mail#gmail.com")
);
So $array is an array of associated arrays. To print all values in it, do the following:
// Loop thorugh the $array
for($i=0;$i<count($array);$i++)
{
echo 'Printing '.$i.' row';
// Loop through each element of the $array
foreach($array[$i] as $key=>$value)
{
echo $key." = ".$value.PHP_EOL;
}
echo PHP_EOL;
}
Related
From PHP code I want to create an json array:
[
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"}
]
How can I do this?
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
...
etc.
After that.
json_encode($associativeArray);
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
That's how I am able to do with the help of solution given by #tdammers below.
The following line will be placed inside foreach loop.
$array[] = array('power' => trim("Some value"), 'time' => "time here" );
And then encode the array with json encode function
json_encode(array('newvalue'=> $array), 200)
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.
<?php
// define a JSON Object class
class jsonOBJ {
private $_arr;
private $_arrName;
function __construct($arrName){
$this->_arrName = $arrName;
$this->_arr[$this->_arrName] = array();
}
function toArray(){return $this->_arr;}
function toString(){return json_encode($this->_arr);}
function push($newObjectElement){
$this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
}
function add($key,$val){
$this->_arr[$this->_arrName][] = array($key=>$val);
}
}
// create an instance of the object
$jsonObj = new jsonOBJ("locations");
// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));
$jsonObj->add("location","TestLoc3"); // from key:val pairs
echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>
Will output:
Array
(
[locations] => Array
(
[0] => Array
(
[location] => TestLoc1
)
[1] => Array
(
[location] => TestLoc2
)
[2] => Array
(
[location] => TestLoc3
)
)
)
{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}
To iterate, convert to a normal object:
$myObj = $jsonObj->toArray();
Then:
foreach($myObj["locations"] as $locationObj){
echo $locationObj["location"] ."<br />";
}
Outputs:
TestLoc1 TestLoc2 TestLoc3
Access direct:
$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];
A practical example:
// return a JSON Object (jsonOBJ) from the rows
function ParseRowsAsJSONObject($arrName, $rowRS){
$jsonArr = new jsonOBJ($arrName); // name of the json array
$rows = mysqli_num_rows($rowRS);
if($rows > 0){
while($rows > 0){
$rd = mysqli_fetch_assoc($rowRS);
$jsonArr->push($rd);
$rows--;
}
mysqli_free_result($rowRS);
}
return $jsonArr->toArray();
}
How to put these codes in a foreach loop?
$item1_details = array(
'id' => 'a1',
'price' => 18000,
'quantity' => 3,
'name' => "Apple"
);
$item2_details = array(
'id' => 'a2',
'price' => 20000,
'quantity' => 2,
'name' => "Orange"
);
Then the array above will be saved in a variable. It's an array. And, yes, I have no idea how to do a loop inside array. So please help me for this too.
$item_details = array ($item1_details, $item2_details);
Thus, I have to questions. First, how to create an array inside a foreach loop. Second, How to loop inside an array.
You don't put a loop inside an array, you push onto the array in a loop.
$item_details = array();
for ($i = 0; $i < 10; $i++) {
$item_details[] = $item1_details;
$item_details[] = $item2_details;
}
This will make an array with 10 alternating copies of $item1_details and $item2_details.
You mentioned a foreach loop, but that's for looping over an array that already exists. You didn't show any array to loop over, so I'm not sure how it applies in this case.
You can use array_values with array_merge
$f = array_merge(array_values($item1_details), array_values($item2_details));
Working example :- https://3v4l.org/fDM3N
I have a nested assocative array which might look something like this:
$myarray = array(
['tiger'] => array(
['people'], ['apes'], ['birds']
),
['eagle'] => array(
['rodents'] => array(['mice'], ['squirrel'])
),
['shark'] => ['seals']
);
How can I loop through the first layer (tiger, eagle, shark) in a random order and ensure that I cover them all in my loop? I was looking at the PHP function shuffle();, but I think that function messes up the whole array by shuffling all layers.
You can randomly sort an array like this, it will keep the keys and the values
<?php
$myarray = array(
'tiger' => array(
'people', 'apes', 'birds'
),
'eagle' => array(
'rodents' => array('mice', 'squirrel')
),
'shark' => 'seals'
);
$shuffleKeys = array_keys($myarray);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $myarray[$key];
}
print_r($newArray);
You can get the keys using array_keys(). Then you can shuffle the resulting key array using shuffle() and iterate through it.
Example:
$keys = array_keys($myarray);
shuffle($keys);
foreach ($keys as $key) {
var_dump($myarray[$key]);
}
According to my test, shuffle only randomizes 1 layer. try it yourself:
<?php
$test = array(
array(1,2,3,4,5),
array('a','b','c','d','e'),
array('one','two','three','four','five')
);
shuffle($test);
var_dump($test);
?>
From PHP code I want to create an json array:
[
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"},
{"region":"valore","price":"valore2"}
]
How can I do this?
Easy peasy lemon squeezy: http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
There's a post by andyrusterholz at g-m-a-i-l dot c-o-m on the aforementioned page that can also handle complex nested arrays (if that's your thing).
Use PHP's native json_encode, like this:
<?php
$arr = array(
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
),
array(
"region" => "valore",
"price" => "valore2"
)
);
echo json_encode($arr);
?>
Update: To answer your question in the comment. You do it like this:
$named_array = array(
"nome_array" => array(
array(
"foo" => "bar"
),
array(
"foo" => "baz"
)
)
);
echo json_encode($named_array);
Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:
$a = array(
array('foo' => 'bar'),
array('foo' => 'baz'));
$json = json_encode($a);
Gives you:
[{"foo":"bar"},{"foo":"baz"}]
Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.
After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.
$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';
...
etc.
After that.
json_encode($associativeArray);
also for array you can use short annotattion:
$arr = [
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
],
[
"region" => "valore",
"price" => "valore2"
]
];
echo json_encode($arr);
That's how I am able to do with the help of solution given by #tdammers below.
The following line will be placed inside foreach loop.
$array[] = array('power' => trim("Some value"), 'time' => "time here" );
And then encode the array with json encode function
json_encode(array('newvalue'=> $array), 200)
Just typing this single line would give you a json array ,
echo json_encode($array);
Normally you use json_encode to read data from an ios or android app. so make sure you do not echo anything else other than the accurate json array.
I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.
<?php
// define a JSON Object class
class jsonOBJ {
private $_arr;
private $_arrName;
function __construct($arrName){
$this->_arrName = $arrName;
$this->_arr[$this->_arrName] = array();
}
function toArray(){return $this->_arr;}
function toString(){return json_encode($this->_arr);}
function push($newObjectElement){
$this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
}
function add($key,$val){
$this->_arr[$this->_arrName][] = array($key=>$val);
}
}
// create an instance of the object
$jsonObj = new jsonOBJ("locations");
// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));
$jsonObj->add("location","TestLoc3"); // from key:val pairs
echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>
Will output:
Array
(
[locations] => Array
(
[0] => Array
(
[location] => TestLoc1
)
[1] => Array
(
[location] => TestLoc2
)
[2] => Array
(
[location] => TestLoc3
)
)
)
{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}
To iterate, convert to a normal object:
$myObj = $jsonObj->toArray();
Then:
foreach($myObj["locations"] as $locationObj){
echo $locationObj["location"] ."<br />";
}
Outputs:
TestLoc1 TestLoc2 TestLoc3
Access direct:
$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];
A practical example:
// return a JSON Object (jsonOBJ) from the rows
function ParseRowsAsJSONObject($arrName, $rowRS){
$jsonArr = new jsonOBJ($arrName); // name of the json array
$rows = mysqli_num_rows($rowRS);
if($rows > 0){
while($rows > 0){
$rd = mysqli_fetch_assoc($rowRS);
$jsonArr->push($rd);
$rows--;
}
mysqli_free_result($rowRS);
}
return $jsonArr->toArray();
}
Hi I'm trying to loop through a array and set a keys value. Very basic question.
The Code I tried is below.
http://pastebin.com/d3ddab156
<?php
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as $item)
{
$item['setTest'] = 'bob';
}
print_r($testArray);
I imagine I'm missing something stupid here and it is going to be a D'oh! moment for me. What is wrong with it?
Thanks.
You do:
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as $item)
{
$item['setTest'] = 'bob';
}
print_r($testArray);
$item is a copy. You change the copy, not the real array. Try this:
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as $key => $item)
{
$testArray[$key]['setTest'] = 'bob';
}
print_r($testArray);
Or, if you have a lot of data in the array and want to avoid creating a complete copy of each element over every iteration, simply iterate over each element as a reference. Then only a reference to that item is created i memory and you can directly manipulate the array element by using $item:
$testArray = array("bob1" => array( 'name' => "bob1", 'setTest' => '2'));
foreach($testArray as &$item)
{
$item['setTest'] = 'bob';
}
print_r($testArray);
NOTE: be sure to unset $item after the loop so you don't inadvertantly modify the array later by using that variable name.