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 :)
Related
I have the following PHP code:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
I want to be able to get the second value in a nested array by identifying a first. eg: if_exists("Donald") would return "trump".
I've tried to recurse through the array but I'm at a loss on how to select the second value once the first is identified.
Any help would be appreciated
You can use something like this:
$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);
$search_val = "Donald";
$key = array_search($search_val, array_column($special_files,0));
$output = $special_files[$key][1]; //outputs "Trump"
Here is a working sample.
Well, you can try the following:
foreach ($special_files as $special_file) {
$i = 1;
foreach ($special_file as $element) {
if ($i==2) {
echo ("Second value is: " . $element);
break;
}
$i++;
}
}
You can extract the [1] elements and index them by the [0] elements:
$lookup = array_column($special_files, 1, 0);
$result = isset($lookup['Donald']) ?: false;
The $lookup array yields:
Array
(
[Turnip] => Tweed
[Donald] => Trump
)
I want to know what is the value of the 2nd index of my array.
I have something like this:
$a[][1]= 10;
$a[][0]= 20;
$a[][1]= 12;
$a[][0]= 25;
I want to get only the values from $a wich 2nd index is 1.
I need to do a comparison and if the answer is correct, get the value
From this example, elements will be:
$a[0][1]
$a[2][1]
I know about array_key_exists but i dont know how to use it with Multidimensional arrays.
Any help?
Thanks.
Solution I was looking for.
$a = array();
$a[][1] = b1;
$a[][0] = b2;
$a[][0] = c1;
$a[][1] = c2;
foreach ($a AS $key => $aVal )
if (array_key_exists(1,$aVal))
echo $a[$key][1] . "<br>";
Have you tried isset($a[$specified_index])?
Here is some code:
foreach ( $a AS $key => $aVal ) {
if ( array_key_exists(1,$aVal) ) {
var_dump($key,$aVal);
}
}
foreach($a as $key => $value)
{
if(isset($value[1]))
{
if($value[1] == 1)
{
echo "value is 1";
}
else
{
echo "value is not 1 but is ".$value[1];
}
}
}
thx to #Havelock
This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
i want so replace something in a array, but the array isn´t sorted. So maybe you know how i can fix the problem.
I´ve a array with a few of this element.
<media type="image" id="image5" label="book5.jpg" group="image" source="list2/Schuh2.jpg" url="image5/0.jpg" icon="image5/0.jpg"/>
How can i sort the array by the value of lable? so that first i get for example from
Lables:
book3
book4
book2
-->
book2
book3
book4
i hope you know what i mean :D thank you ;-)
$books = array('book3', 'book4', 'book2');
sort($books);
or
$books = array('label1' =>'book5.jpg',
'label2' => 'book4.jpg', 'label3' => 'book3.jpeg');
asort($books); // sorts by value (ascending)
hope this helps!
Hack
foreach($a as $k => $media) {
$parts = explode(' ',$media);
foreach($parts as $part) {
$kv = explode('=', $part);
if ($kv[0] == 'label') {
$a[$kv[1]] = $media;
unset($a[$k]);
}
}
}
ksort($a);
or look at usort() which let you use your own comparison function
Assuming unique book#.jpg images you could do something like ...
<?php
$sortedArray = array();
foreach ($unsortedArray as $item ) {
$sortedArray[explode('.', explode('label="book', $item)[1])[0]] = $item;
}
ksort($sortedArray);
foreach ($sortedArray as $item ) {
echo $item;
}
?>
I did not test this.
UPDATE:
Someone else's suggestion to use usort() is a good one. Something like this ...
<?php
function compareElements($a, $b) {
$aNum = explode('.', explode('label="book', $a)[1])[0];
$aNum = explode('.', explode('label="book', $b)[1])[0];
return ($aNum < $bNum) ? -1 : 1;
}
usort($arrayOfElements, "compareElements");
foreach ($arrayOfElements as $element) {
echo $element;
}
?>
The Problem was, that i can´t sorte bei the one value ['id'] so i has create me one array with all the Informations, and a second only with the ['id'] of the pictures.
Input and load the XML-File.
$mashTemplateFile = 'C:\Users\...\test.xml';
$mashTemplate = simplexml_load_file($mashTemplateFile);
$mash = $mashTemplate->mash;
declare the arry's
$imageArrayMedTemp = array();
$imageArrayMedID = array();
$imageArrayMed = array();
put all the information from the media in the array $imageArrayMedTemp and only the ['id']into the array $imageArrayMedID.
foreach ($mash->media as $med) {
if ($med['type'] == 'image') {
array_push($imageArrayMedTemp , $med);
array_push($imageArrayMedID , $med['id']);
}
now i sort the array with the ['id']'s
natsort($imageArrayMedID);
after sorting i will put the information from the array $imageArrayMedTemp into a new array $imageArrayMed, storing by when the key of both is the same.
foreach ($imageArrayMedID as $key1 => $value1) {
foreach ($imageArrayMedTemp as $key2 => $value2) {
if($key1 == $key2){
array_push($imageArrayMed,$value2);
}
}
}
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;
}