i've a 2-dimensional array and i want to push values to it with a while loop like;
$arr[0][1] = 1. value
$arr[0][2] = 2. value
i ve tried
while($zRow = mysql_fetch_array($zQuery))
{
$props[]['name'] =$zRow['name'];
$props[]['photo'] =$zRow['thumbnail'];
}
this loop pushes name to $props[0][name] and thumbnail to $props[1][photo]
i also tried
$j = 0;
while($zRow = mysql_fetch_array($zQuery))
{
$props[$j]['name'] =$zRow['name'];
$props[$j]['photo'] =$zRow['thumbnail'];
$j+=1;
}
that works but with this i when i use foreach loop later, it makes trouble like "Illegal offset type"
and here is my foreach loop
foreach($props as $no)
{
echo $props[$no]['name'];
}
now my questions;
1) are there any other way than while loop with $j variable like array_push for 2-dimensional arrays
2)how can i use foreach loop for 2-dimensional arrays
You could change the first loop to the following:
while($zRow = mysql_fetch_array($zQuery))
{
$row = array();
$row['name'] = $zRow['name'];
$row['photo'] = $zRow['thumbnail'];
$props[] = $row;
}
Your method also works, but you need that extra variable.
In your second loop, what you actually need to be doing is:
foreach($props as $index => $array)
{
echo $props[$index]['name'];
// OR
echo $array['name'];
}
Pushing anything onto an array with $myArray[] = 'foo' will increment the array's counter.
For multidimensional array, you need to populate the "inner" array, then push it to the "outer" (in your case $props) array.
while($zRow = mysql_fetch_array($zQuery)) {
$data = array('name' => $zRow['name'], 'photo' => $zRow['thumbnail']);
$props[] = $data;
}
To iterate over multidimensional arrays whose depth is known:
foreach ($props as $prop) {
foreach ($prop as $key => $value) {
echo "{$key} => {$value}" . PHP_EOL;
}
}
If the depth of the nesting is not known, you may have to use a recursive function to gather the data.
Related
I need to generate a JSON Object and push it to a JSON object array using PHP.
This is my code.
public function getJSONData()
{
$csv = $this->getCsvData();
$finalArray = array();
// First foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Second foreach to iterate the headlines array.
$newArray = array();
foreach ($csv["headlines"] as $index => $headline) {
// $newArray[$key]->$csv["headlines"] = $value;
// print_r($headline);
// print_r($value[$index]);
// echo " ";
array_push($newArray, array($headline => $value[$index]));
}
echo json_encode($newArray);
echo "<br>";
array_push($finalArray, json_encode($newArray));
}
// dd($finalArray);
}
From this code, I'm getting the following response.
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12348},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
[{"ID":12349},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":349.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":639.95}]
[{"ID":12350},{"Status":1},{"Manufacturere_ID":101},{"Famiy_matchcode":"101-iphone-11"},{"Name":"iPhone 11"},{"Price":509.95}]
But it is not a valid JSON and I really need to get an output like this:
[{"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":639.95}, {"ID":12348,"Status":1,"Manufacturere_ID":101,"Famiy_matchcode":"101-iphone-11","Name":"iPhone 11","Price":509.95}]
This is a standard JSON object array.
In my code, I'm using array_push($newArray, array($headline => $value[$index])); to generate the array and take it as JSON.
Please help me on this.
You seem to be creating arrays and adding json data in several places, build the data as a normal array and then encode the result...
// Foreach to iterate the data array.
foreach ($csv["data"] as $key => $value) {
// Combine headers with data and add to final result
$finalArray[] = array_combine($csv["headlines"], $value);
}
echo json_encode($finalArray);
I'm trying to read an array to save some values but it doesnt work! Here's my code:
$array=$_POST['idprod'];//I get my array and save it on a var
print_r($array); //It has ALL the data (I use a print_r($array); And YES!! It has the information i need)
$ids[]=explode(',',$array);//Substring to my var
for( $contador=0; $contador <count($ids); $contador++ )
{
echo $ids[$contador].'<br/>';
}
It shows me Array to string conversion in...
What could I do?
use foreach Instead for loop
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
foreach ($array => $var ) {
// do any thing
}
replace
$ids[]=explode(',',$array);//Substring to my var
for( $contador=0; $contador <count($ids); $contador++ ) {
echo $ids[$contador].'<br/>';
and set
$ids = explode(',',$array);
foreach($ids as $id) {
echo $id ."<br>";
}
You only need to explode(), if the incomming data is a comma separated string.
$string = $_POST['idprod'];
$array= explode(',', $string); // split the comma separated values into an array
for($i=0; $i<count($array); $i++)
{
echo $array[$i] . '<br/>';
}
Else you can directly work with the incomming array:
$array = $_POST['idprod'];
for($i=0; $i<count($array); $i++)
{
echo $array[$i] . '<br/>';
}
I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}
I'm having some trouble understanding the coding in PHP, when it comes to multidimensional arrays and how to push.
The idea is to push a "Attribute" and a "Attribute value"
I have tried the formula below
$i = 0;
$array = array();
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[] = ($strAtt => $strVal);
The $array[] = ($strAtt => $strVal); doesnt give me much success.
I have tried array_push($array, $strAtt => $strVal) - no luck..
As an extra questions, how do I loop trough the array and print me multidimensional values ?.
NEW CODE
while ($z->name === 'RECORD')
{
$node = new SimpleXMLElement($z->readOuterXML());
$Print = FALSE;
$output = "";
$i = 0;
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[$strAtt] = $strVal;
if(($i == 6) && ($node->PROP[$i]->PVAL == $ProductLookup))
{
$Print = TRUE;
$Product = $node->PROP[$i]->PVAL;
}
$i++;
}
if($Print == TRUE) {
echo $output;
echo "Product : ".$Product."<br>";
var_dump($array);
}
//print_r($array);
$print = FALSE;
// go to next <product />
$z->next('RECORD');
}
New code added. For some reason my $array is totally empty when i dump it, although my $Output is full of text ?
It sounds like you are wanting an "associative" array and not necessarily a multi-dimensional array. For associative arrays you don't use array_push. Just do this:
$array[$strAtt] = $strVal;
Then to loop the array just do this:
foreach ($array as $key => $value) {
echo "$key = $value\n";
}
Go through array in php , you will understand how array works in php.
Besides if you want to add an element to a multidimensional array you can achieve like this :
$node = array ("key1"=> array (a,b) , "key2"=> array (c,d));
$array = array();
foreach ($node as $key=>$value) {
$array [$key] = $value;
}
This will be the resulting $array after the loop :
array (
"key1"=> array (
a,b
) ,
"key2"=>
array (c,d)
)
Hope that helps , happy coding :)
How do I get the current index in a foreach loop?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
In your sample code, it would just be $key.
If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:
$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}
Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.
This is the most exhaustive answer so far and gets rid of the need for a $i variable floating around. It is a combo of Kip and Gnarf's answers.
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_keys( $array ) as $index=>$key ) {
// display the current index + key + value
echo $index . ':' . $key . $array[$key];
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}
Hope it helps someone.
foreach($array as $key=>$value) {
// do stuff
}
$key is the index of each $array element
$i = 0;
foreach ($arr as $key => $val) {
if ($i === 0) {
// first index
}
// current index is $i
$i++;
}
The current index is the value of $key. And for the other question, you can also use:
current($arr)
to get the first element of any array, assuming that you aren't using the next(), prev() or other functions to change the internal pointer of the array.
You can get the index value with this
foreach ($arr as $key => $val)
{
$key = (int) $key;
//With the variable $key you can get access to the current array index
//You can use $val[$key] to
}
$key is the index for the current array element, and $val is the value of that array element.
The first element has an index of 0. Therefore, to access it, use $arr[0]
To get the first element of the array, use this
$firstFound = false;
foreach($arr as $key=>$val)
{
if (!$firstFound)
$first = $val;
else
$firstFound = true;
// do whatever you want here
}
// now ($first) has the value of the first element in the array
You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.
<?php
$array = array('test', '1', '2');
$keys = array_keys($array);
var_dump($keys[0]); // int(0)
$array = array('test'=>'something', 'test2'=>'something else');
$keys = array_keys($array);
var_dump(array_search("test2", $keys)); // int(1)
var_dump(array_search("test3", $keys)); // bool(false)
well since this is the first google hit for this problem:
function mb_tell(&$msg) {
if(count($msg) == 0) {
return 0;
}
//prev($msg);
$kv = each($msg);
if(!prev($msg)) {
end($msg);
print_r($kv);
return ($kv[0]+1);
}
print_r($kv);
return ($kv[0]);
}
based on #fabien-snauwaert's answer but simplified if you do not need the original key
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_values( $array ) as $index=>$value ) {
// display the current index + value
echo $index . ':' . $value;
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}