PHP push associative array in normal array - php

I have to push an associative array in a normal array (not to convert).
Example (NO CODE):
project = {}
element["title"] = "My title"
element["description"] = "My description"
is there a way to have this
echo $project->title;
//or
echo $project[0]["title"]
?
I'v tried this, but server says: ERROR 500
$i = 0;
$projects = {};
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}

$projects = {}; is not valid php.
If you want to initialize an empty array (associative or numeric, that does not matter), you need:
$projects = [];
or on older php versions:
$projects = array();
Also note that you need to do the same to your $elements array at the beginning of each iteration otherwise it will grow on every iteration. Assuming that the descriptions are not all the same...
foreach($projectsElements as $element) {
$elements = [];
while($i <= $nRowsForProject) {
...
And your while loop does not seem to make a lot of sense: You are not using the $i variable in your loop so are just doing the same assignments on each iteration.

$projects = []; // declare empty array
foreach($projectsElements as $element) {
$projects []= $element; // push $element into $projects array
}

$i = 0;
$projects = array();
foreach($projectsElements as $element) {
while($i <= $nRowsForProject) {
$elements = array();
$idSection = $element->idSection;
if($idSection == 1) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 2) $elements["".$element->internalDescription.""] = $element->text;
else if($idSection == 3) $elements["".$element->internalDescription.""] = $element->text;
$i++;
}
array_push($projects,$elements);
$i=0;
}

Related

PHP Reformat content array and Count same value

I have dynamically array for example like this:
[{"Name":"Sutejo","status":"Overload"},{"Name":"Paiman","status":"Overload"},{"Name":"Agung Hercules","status":"Idle"},{"Name":"Heru","status":"Busy"}]
How should i do if want to make my array become like this ? (count if status has same value and combine to be array again)
Expected output:
[{"Overload":"2"},{"Idle":"1"},{"Busy":"1"}]
So far my code just like this:
public function getData(){
$key_idle = 0;
$key_busy = 0;
$key_overload = 0;
$data = $this->queries_trend->getDataCustomer();
//print_r(json_encode($data));
foreach ($data as $key => $value) {
$val = $value['status'];
if ($val == 'Idle') {
$key_idle = $key_idle + 1;
} elseif ($val == 'Busy') {
$key_busy = $key_busy + 1;
} elseif ($val == 'Overload') {
$key_overload = $key_overload + 1;
}
}
}
You can use array_count_values function:
$statuses = array_count_values(array_column($list, 'status'));

working with two arrays in foreach, is this example possible?

I'm working with two arrays, $local and $national. Currently, they're both within their own separate foreach loops, which I'm using as follows:
$list // 1st array
$national // 2nd array
$numberlist = array();
$numbernational = array();
foreach($list as $rows)
{
// here I have a bunch of code that defines the variable $cheapestdeliverydate
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
}
}
foreach($national as $rows)
{
// here I have a bunch of code that defines the variable $cheapestdeliverydate
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numbernational[] = $rows;
}
}
Is there a way however to merge these two foreach functions? I've tried the following:
foreach(array_merge($list, $national) as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
$numbernational[] = $rows;
}
}
But unfortunately when I do a print_r on both $numberlist and $numbernational, they're both returning the exact same array. In hindsight this makes sense to me now, so I wonder if I can do something along the lines of:
foreach($list as $row, $national as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $row;
$numbernational[] = $rows;
}
}
Both the $list and $national arrays are the same size.
You can iterate over both arrays in a single pass using SPL's MultipleIterator
$numberlist = [];
$numbernational = [];
$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($list));
$mi->attachIterator(new ArrayIterator($national));
$result = array();
foreach($mi as list($listRow, $nationalRow)) {
if (strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate)) {
$numberlist[] = $listRow;
$numbernational[] = $nationalRow;
}
}
Due to logic of your code, it must be just
$list // 1st array
$national // 2nd array
$numberlist = array();
$numbernational = array();
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate)
{
$numberlist = $list;
$numbernational = $national;
}
Try something like:
$all = array_merge($list, $national);
foreach($all as $rows)
{
if(strtotime(date('DjMY', strtotime($_GET['inputDate']))) >= strtotime($cheapestdeliverydate))
{
$numberlist[] = $rows;
$numbernational[] = $rows;
}
}

End php if statement

I compare a string from a feed with another variable and echo a corresponding string.
$xml = #simplexml_load_file($feed);
foreach ($xml->entry as $entry) {
$caller = $entry->caller[0];
$message = $entry->message[0];
}
if (($caller == $id) {
echo '$message';
}
I want to echo no more than 5 messages, regardless of the number of ($caller == $id) matches.
$x=1;
while (($caller == $id) && ($x<=5)) {
echo '$x $message';
$x++;
}
That general approach has failed.
I thought maybe I could put the condition in a function and call it a certain number of times but no luck.
function myFunction(){
echo '$message';
}
$x=1;
while($x<=5) {
echo '$x';
myFunction();
$x++;
}
For one, your while loop would actually only output 4 results because you are saying while x is LESS than 5, not <= 5. You can leave it < 5, but change x to equal 0 instead of 1;
The second problem is that as soon as $caller does not == $id, your while loop will stop. You should only need to use a foreach loop for this, not both a foreach to extract the data and a while to loop over it again.
The third problem with your code is that you are writing your caller and message values to the same variable over and over in your foreach. Then, in your while loop, your $caller and $message variables will always be equal to the last items in the $xml->entry array.
$xml = #simplexml_load_file($feed);
$number_of_results_to_show = 5;
$x = 0; // counter
foreach ($xml->entry as $entry) {
$caller = $entry->caller[0];
$message = $entry->message[0];
if ($caller == $id && $x < $number_of_results_to_show) {
$x++;
echo $message;
}
// also, you can use a break to prevent your loop from continuing
// even though you've already output 5 results
if ($x == $number_of_results_to_show) {
break;
}
}
I assume that you have an array $xml->entry and you want to print message[0] of up to 5 array elements. Message is printed if $caller matches $id.
$xml = #simplexml_load_file($feed);
// Iterate through $xml->entry until the end or until 5 printed messages
for($i = 0, $j = 0; ($i < count($xml->entry)) && ($j < 5); ++$i) {
$caller = $xml->entry[$i]->caller[0];
$message = $xml->entry[$i]->message[0];
if ($caller == $id) {
echo "$message";
++$j;
}
}
If you want to store results from $xml->entry then:
$xml = #simplexml_load_file($feed);
$storedResults = new array();
foreach($xml->entry as $entry) {
$caller = entry->caller[0];
$message = entry->message[0];
// Store data in array. $storedResults will be an array of arrays
array_push(storedResults, array( 'caller' => $caller, 'message' => $message ));
}
// Print up to 5 messages from the stored results
$i = 0, $j = 0;
while (($i < count($storedResults)) && ($j < 5)) {
if ($storedResults[$i]['caller'] == $id) {
echo $storedResults[$i]['message'];
++$j;
}
++$i;
}

Counting the number of dimensions in an array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a way to find how how “deep” a PHP array is?
I am trying to write a method to count the number of dimensions of an array. The following gives me a correct count of dimensions
$array = array();
$array[0] = array();
$array[0][0] = 0;
$array[0][1] = array();
$array[0][1][0] = 10;
$array[0][1][1] = 11;
echo '<p>'.\utility\arrayTools\arrayTools::numberOfDimensions($array).'</p>';
//3 Dimensons
The second examples also gives me a correct count of the number of dimensions
$array = array();
$array[0] = array();
$array[0][0] = 0;
$array[0][1] = array();
$array[0][1][0] = 10;
$array[0][1][1] = 11;
$array[1] = 1;
$array[2] = 2;
//3 Dimensions
But the following example gives me too high of a count
$array = array();
$array[0] = array();
$array[0][0] = 0;
$array[0][1] = array();
$array[0][1][0] = 10;
$array[0][1][1] = 11;
$array[1] = 1;
$array[2] = 2;
$array[3] = array();
$array[3][0] = 30;
//Should still be 3 dimensions, but gives me 4
The method I am using is below
//Method
public static function numberOfDimensions($array)
{
if(func_num_args() === 2){
if(is_int(func_get_arg(1))){
$number_of_dimensions = func_get_arg(1);
}else{
throw new Exception('The second argumment must be an interger');
}
}else{
$number_of_dimensions = 0;
}
if(is_array($array) === TRUE){
$number_of_dimensions++;
if(self::isMultiDimensional($array) === TRUE){
foreach($array as $iteration){
$number_of_dimensions = self::numberOfDimensions($iteration,$number_of_dimensions);
}
return $number_of_dimensions;
}else{
return $number_of_dimensions;
}
}else{
return $number_of_dimensions;
}
}
I already know the problem is it is still adding for every multidimensional even though the count may be equal to or less then the number of dimensions. But what I can't figure out is how to get it to find the highest number of dimensions and stop counting
Here is a simpler version of your script
function numberOfDimensions($array) {
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$d = 0;
foreach ( $it as $v )
$it->getDepth() >= $d and $d = $it->getDepth();
return ++ $d;
}
From another answer here on SO:
function array_depth($array) {
$max_depth = 1;
foreach ($array as $value) {
if (is_array($value)) {
$depth = array_depth($value) + 1;
if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}
return $max_depth;
}
I havn't written any PHP in a very long while, so there may very well be mistakes in my code, excuse me in advance.
function numberOfDimensions($array,$so_far=0){
if !is_array($array){
return 0;
}
$max_dims = 0;
foreach($array as $element){
$element_dims = numberOfDimensions($array);
$max_dims = max($max_dims,$element_dims);
}
return $max_dims +1;
}
This function assumes it is being called with an array as parameter, thus the minimum depths is 1.
It then recursively looks at all child elements, and if the child is deeper than already known, it add the depth of the child to the calculated depth:
function numberOfDimensions($subject) {
// scalar value has depth 0
if(!is_array($subject)) return 0;
// array has min depth of 1
$depth = 1;
foreach ($subject as $element) {
if (is_array($element)) {
// is the sub array deeper than already known?
$sub_depth = numberOfDimensions($element);
if ($sub_depth >= $depth) {
$depth += $sub_depth;
}
}
}
return $depth;
}

Nested sets, php array and transformation

I need to transform my nested sets structure (mysql) into json for this spacetree
1) http://blog.thejit.org/wp-content/jit-1.0a/examples/spacetree.html
I found this function to create an array from nested sets:
2) http://semlabs.co.uk/journal/converting-nested-set-model-data-in-to-multi-dimensional-arrays-in-php
I can also convert php array into json with PHP function json_encode
My problem: the function nestify (from second link) gives me not exactly that i need. I need something like this: http://pastebin.com/m68752352
Can you help me change the function "nestify" so it gives me the correct array?
Here is this function one more time:
function nestify( $arrs, $depth_key = 'depth' )
{
$nested = array();
$depths = array();
foreach( $arrs as $key => $arr ) {
if( $arr[$depth_key] == 0 ) {
$nested[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
else {
$parent =& $nested;
for( $i = 1; $i <= ( $arr[$depth_key] ); $i++ ) {
$parent =& $parent[$depths[$i]];
}
$parent[$key] = $arr;
$depths[$arr[$depth_key] + 1] = $key;
}
}
return $nested;
}
The following snippet should do the trick, adapted from some PHP Doctrine code I found on the web :
function toHierarchy($collection)
{
// Trees mapped
$trees = array();
$l = 0;
if (count($collection) > 0) {
// Node Stack. Used to help building the hierarchy
$stack = array();
foreach ($collection as $node) {
$item = $node;
$item['children'] = array();
// Number of stack items
$l = count($stack);
// Check if we're dealing with different levels
while($l > 0 && $stack[$l - 1]['depth'] >= $item['depth']) {
array_pop($stack);
$l--;
}
// Stack is empty (we are inspecting the root)
if ($l == 0) {
// Assigning the root node
$i = count($trees);
$trees[$i] = $item;
$stack[] = & $trees[$i];
} else {
// Add node to parent
$i = count($stack[$l - 1]['children']);
$stack[$l - 1]['children'][$i] = $item;
$stack[] = & $stack[$l - 1]['children'][$i];
}
}
}
return $trees;
}

Categories