How to use array_push with associative array and index key?
Asked Answered
E

1

6

I am a bit 'rusty with php as it happens that sometimes I use it for weeks and sometimes it happens that you do not use for months. Either way I'm trying to pass values of another array are "array", on another array in an orderly manner ... What I want to do is essentially create a key that allows me to organize incremental values per line, in particular;

array content

Array 
(
    [key] => value
    [2] => 1 
    [3] => Inter 
    [4] => 4 
    [5] => 4 
    [6] => 0 
    [7] => 0 
    [8] => 5 
    [9] => 1
    [10] => +4
    [11] => 12
    [12] => Chievo Verona - Inter 0 - 1
    [13] => Inter - Milan 1 - 0
    [14] => Carpi - Inter 1 - 2
    [15] => Inter - Atalanta 1 - 0
    [16] => ;
    [17] => 2
    [18] => Torino
    [19] => 4
    [20] => 3
    [21] => 1
    [22] => 0
    [23] => 9
    [24] => 4
    [25] => +5
    [26] => 10
    [27] => Torino - Sampdoria 2 - 0
    [28] => Hellas Verona - Torino 2 - 2
    [29] => Torino - Fiorentina 3 - 1
    [30] => Frosinone - Torino 1 - 2
    [31] => ;
    [32] => 3
    [33] => Fiorentina
    [34] => 4
    [35] => 3
    [36] => 0
    [37] => 1
    [38] => 5
    [39] => 3
    [40] => +2
    [41] => 9
    [42] => Carpi - Fiorentina 0 - 1
    [43] => Fiorentina - Genoa 1 - 0
    [44] => Torino - Fiorentina 3 - 1
    [45] => Fiorentina - Milan 2 - 0
    [46] => ;
    [47] => 4
    [48] => Roma
    [49] => 4
    [50] => 2 

the ";" It'll need to be able to recognize where you break the line, I do not remember if there is any method that allows me to access the next key.

Currently my code is:

$classifica = array("key" => "value");
function buildArrayClassifica()
{
    global $array; 
    global $classifica;

    $i = 0; 

    foreach(array_slice($array,1)  as $key => $value) 
    {
        if($value != ";")
        {
            array_push($classifica[$i], $value); //there is a problem
            echo $value . " ";
        }
        else if($value == "value ")
        {
            continue;
        }
        else
        {
            $i++;         
            echo "<br/>";
        }
    }
}

The code I will return this error:

Warning: array_push () Expects parameter 1 to be array, null given in...

in particular on array_push, it seems not to accept incremental keys or maybe I'm doing it the wrong way. Can anyone tell me how to solve?

UPDATING

As you have seen the issue is not simple and it is quite difficult to explain the problem, but I will try to be even clearer to meet. As you can see above you are the structure of the array "array", but is a disordered structure that needs to be ordered in an additional array. To recapitulate the structure of the array "array" is:

1 , Inter , 4 , 4 , 0 , 0 , 5 , 1 , +4 , 12 , Chievo Verona - Inter 0 - 1 , Inter - Milan 1 - 0 , Carpi - Inter 1 - 2 , Inter - Atalanta 1 - 0 , ;

the ";" means that the line is finished. So the next value near the ";" means that a new line coming. What I need is move all the value of "array" in array classifica, but I want organize them for:

ROW1 =>  1 , Inter , 4 , 4 , 0 , 0 , 5 , 1 , +4 , 12 , Chievo Verona - Inter 0 - 1 , Inter - Milan 1 - 0 , Carpi - Inter 1 - 2 , Inter - Atalanta 1 - 0 
ROW2 => Other values...

So the ROW1, 2 .. rapresents the key of the array classifica. I'm trying to push the value inside a row and after it increment $i index but the code doesn't add the value because the index replace in loop the actual key, for example:

actual foreach content:
$i = 0
value = "Inter"
content of array=> [0] => Inter
now the $i is ever 0 because the row isn't finished yet, the ";" 
it has not yet been reached, so the next content of foreach is:
"1" but replace the "Inter" value, so this is a problem.
Exarch answered 22/9, 2015 at 15:25 Comment(15)
If your using a associative array you simply add the key=>value pair to the array ex : $myArray[$myKey] = $myValue; Pushing onto a indexed array is pointless since it's already indexed by the keyMontserrat
Maybe I've understand wrong, but array_push display the same error: array_push($classifica[$i] = $value); //Warning: array_push() expects at least 2 parametersExarch
Bender, get rid of array_push, the code should just be $classifica[$i]=$value;Montserrat
This is convoluted. You need to show what you have/input and what you want/output.Komara
array_push expects the first parameter to be an array to push something onto, and the second parameter should be the value to push onto the array. In your code, you don't pass the array ($classifica), but element $i of the array. Apparently that element doesn't exist, so $classifica[$i] evaluates to null, and you can't push a value onto null. Most likely, your intention is to set item $i to value, in which case the code should be $classifica[$i] = $value as @Montserrat already suggested.Countrybred
It's not possible do this with array_push? Because if I using $classifica[$i] = $value; I lost the key index and the next value in the foreach will be replaced in the same key. I've update the question with the structure of arrayExarch
I'm trying to pass values of another array are "array", on another array in an orderly manner -- I'm struggling with that part, what do you mean with this?Ortiz
Means that the first array called "array" have the values messy, so in the array "classifica" I need to organize. I think to use a boolean variable. I'll update my question with a possible solution. Wait for me.Exarch
@bender, you can use functions to sort the array. Could be easier.Entreaty
Yeah but I also have string in the array not number onlyExarch
Maybe it would be better to provide some example data and what your goal is. In this way, we can advise what functions might be best. I have a feeling the answer I provided will fit your needs, yet is not the best solution in the end.Entreaty
Okay see my update example of the actual situationExarch
@Exarch I don't see any semi-colons (;) in your values. Are you exploding this from a CSV?Entreaty
the first part of code was edit by an user and he forgot to enter;Exarch
Let us continue this discussion in chat.Exarch
E
3

You cannot use array_push() in this way. Please try:

$classifica = array();
function buildArrayClassifica()
{
    global $array; 
    global $classifica;

    $i = 0; 

    foreach(array_slice($array,1) as $key => $value) 
    {
        if($value != ";")
        {
            $classifica[$i] = $value;
            echo $value . " ";
        }
        else if($value == "value ")
        {
            continue;
        }
        else
        {
            $i++;         
            echo "<br/>";
        }
    }
}

This will create indexes (the value of $i) when $value is added to your array. array_push() would place the $value at the next numerical index and may not be what you want by the looks of it. You could also use $key if you wanted the index to match.

EDIT

After more discussion, you have a specific format, where the first Item is the Key, the following indexes are values, and when you encounter the value ";", it starts the sequence over. So when we read:

[2] => 1 
[3] => Inter 
[4] => 4 
[5] => 4 
[6] => 0 
[7] => 0 
[8] => 5 
[9] => 1
[10] => +4
[11] => 12
[12] => Chievo Verona - Inter 0 - 1
[13] => Inter - Milan 1 - 0
[14] => Carpi - Inter 1 - 2
[15] => Inter - Atalanta 1 - 0
[16] => ;

The first value, '1' is our Index, the following values become the Value for this Index, and we stop reading when we find ";". That would look something like:

<?php
function buildArrayClassifica($dataArray){
    $resultArray = array();
    $t = array_values($dataArray);
    print_r($t);
    $lsc = 0;
    foreach($t as $k => $v){
        if((string)$v == ';'){
            echo "<p>Found ';' at [$k] => {$v}</p>";
            // Found end of data
            // Save position
            $scp = $k;
            echo "<p>Recorded [$scp] position for ';'.</p>";
            // Reset to find the Index, first int in this series
            $c=$lsc; // First pass this should be 0
            // Set the index
            if($lsc ==0){
                // First pass
                $index = intval($t[$c]);
                echo "<p>Getting Index from position [" . ($c) ."] => $index for Result Array.</p>";
                $c++;
            } else {
                $c++;
                $index = intval($t[$c]);
                echo "<p>Getting Index from position [" . ($c) ."] => $index for Result Array.</p>";
                $c++;
            }
            echo "<p>Starting to read data from [$c] until [$scp].</p>";
            // Init implode variable
            $data = "";
            for($c;$c<$scp;$c++){
                //Populate variable with the series up to semicolon, skipping first element (index)
                $data .= $t[$c] . ", ";
            }
            echo "<p>Data collected for this round: '" . htmlentities(substr($data,0,-2)) . "'</p>";
            // populate result array
            $resultArray[$index] = substr($data,0,-2);
            echo "<p>resultArray[$index] => " . htmlentities($resultArray[$index]) . "</p><br />";
            $lsc = $scp;
        }
    }

    return $resultArray;
}
$oldArray = array(1, "Inter", 4 , 4 , 0 , 0 , 5 , 1 , "+4" , 12 , "Chievo Verona - Inter 0 - 1", "Inter - Milan 1 - 0", "Carpi - Inter 1 - 2", "Inter - Atalanta 1 - 0", ";", 2, "Torino", 4, 3, 1, 0, 9, 4, '+5', 10, "Torino - Sampdoria 2 - 0", "Hellas Verona - Torino 2 - 2", "Torino - Fiorentina 3 - 1", "Frosinone - Torino 1 - 2", ";", 3, "apple", 0, 4, 6, "apple", ";");

$classifica = buildArrayClassifica($oldArray);
print_r($classifica);
?>

My initial testing seems to work for what you described. The first element of the array becomes the Index, the next few values become imploded until we reach the semicolon (;) value.

What I see as a result:

Array ( [1] => Inter, 4, 4, 0, 0, 5, 1, +4, 12, Chievo Verona - Inter 0 - 1, Inter - Milan 1 - 0, Carpi - Inter 1 - 2, Inter - Atalanta 1 - 0 [2] => Torino, 4, 3, 1, 0, 9, 4, +5, 10, Torino - Sampdoria 2 - 0, Hellas Verona - Torino 2 - 2, Torino - Fiorentina 3 - 1, Frosinone - Torino 1 - 2 [3] => apple, 0, 4, 6, apple ) 

ASIDE

If it were me, I would push it all into an array like so:

$data = array();
for($c;$c<$scp;$c++){
    $data[] = $t[$c];
}
$resultArray[$index] = $data;

Or if you really want a string:

$resultArray[$index] = implode(", ", $data);

Hope that helps.

Entreaty answered 22/9, 2015 at 15:48 Comment(2)
Twisty, just a bit correction: in your code the position value it's skipped, how you can see in my question topic there's an integer value before the name of each team, how to get this value? I've tried to change the lsc value to one without success..Exarch
$lsc is defined as the Last Semi-Colon and is set as 0 to start. We start at $c to look for our first integer to use as the Index, value is assigned to $index. Next pass, $lsc is now 14 for example, we need the next element for Index. We increment $c to 15, get the element for the Index, and increment $c again to 16 and start collecting data. So on our second pass, $c is 14, then 15 (index), and then starts collecting data from 16 until $scp, the current semicolon position. So $index will contain that integer you are looking for in each pass.Entreaty

© 2022 - 2024 — McMap. All rights reserved.