This question already has answers here:
How to re-index all subarray elements of a multidimensional array?
(6 answers)
Closed 2 years ago.
I use a PHP array to store data about all the people a user is following on a website. Here is an example of how I have it set up:
$data = array(
['user1'] => array(
[0] => 'somedata',
[1] => 'moredata',
[2] => array(
[0] => 'Jim',
[1] => 'Bob',
[2] => 'Nick',
[3] => 'Susy',
)
),
);
As you can see, it is $data[user][2] that lists all the friends. The array has this exact appearance with [0] and [1] for keys because that is how var_export() does it. Now my problem is this. When someone unfollows somebody, I use unset() to delete that friend from the array. So if I want to unfollow Bob in the example above, it would be left with Jim, Nick, and Susy.
The only issue now is that the array keys do not renumber properly when they rename. So once Bob is gone it goes from 0 to 2 rather than Nick taking on the array key of 1. Now I can think of ways to do this myself but I would highly prefer if there were some PHP function specifically for solving this issue, that is, renaming these array keys to the proper numerical order. I checked out the sort() function but that seems for alphabetizing array values not keys.
You can use array_values to re index the array numerically.
$newArray = array_values($array);
If you just want to re-index the array at that level, you could simply use array_values();
For example, assuming you are removing the "bob" entry, just call array_values at the level directly above bob after removing it.
unset($data['user1'][2][1]);
$data['user1'][2] = array_values($data['user1'][2]);
I'd use array_values like this:
$data['user1'][2]=array_values($data['user1'][2]);
Here's the full code:
$data = array(
'user1' => array(
'somedata',
'moredata',
array(
'Jim',
'Bob',
'Nick',
'Susy',
)
),
);
unset($data['user1'][2][1]);
var_export ($data['user1'][2]);
echo "\n\n";
$data['user1'][2]=array_values($data['user1'][2]);
var_export($data['user1'][2]);
Result
array (
0 => 'Jim',
2 => 'Nick',
3 => 'Susy',
)
array (
0 => 'Jim',
1 => 'Nick',
2 => 'Susy',
)
See it in action here:
Sandbox
You could use array_splice
$removedElement = array_splice($data['user1'][2], $indexOfUserToRemove, 1);
This alters the original array reindexing it, but only if the keys of the array are numeric.
Related
This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed 6 years ago.
I wonder why I don't get the 3 elements of my array.
$array1 = array(
"One" => 1,
"Two" => 2,
"One" => 1
);
When I print it:
echo 'array1:<pre>'; print_r($array1); echo '</pre>';
I get this:
array1:
Array
(
[One] => 1
[Two] => 2
)
This is not what I want. I need to show the following:
array1:
Array
(
[One] => 1
[Two] => 2
[One] => 1
)
Any help wil be appreciated.
Thanks in advance
Your array is a set of key/value pairs. Think of it as a dictionary:
array( "elephant" => "Big grey animal with tusks",
"canary" => "Little Yellow Bird",
"elephant" => "Candy that tastes like Skittles"
)
When you print this one, you will always get the second definition of "elephant", just like in your code. Try changing the second "one" => 1 to "one" => 77.
Because PHP reads from top-down, the last one will always be the final answer, just like in variables.
You can't have duplicate keys in an array. So by declaring the array['one'] you might replace the old value set before for key array['one'].
Use array of array..I think you are trying to achieve that..
But this looks weird
array( ['one'] => array(1,3), ['two']=> 2);
I have an array in PHP that looks like
Array ( [123654] => Array ( [0] => 123456789123456789 [1] => 1 [2] => 06/24/2011 [3] => 06/24/2012 [4] => 12355.44 [5] => 55321.55 ) )
I know in javascript I could access the data I need by doing array[0][0], how would I go about doing this in PHP. It is the 123456789123456789 value that I'm looking at getting.
Try this
array_slice($array, 0, 1);
http://php.net/array_slice
If you don't know the exact keys, you could do something like this:
$a = array_values($my_array);
$b = array_values($a[0]);
echo $b[0];
array_values replaces the keys by simple numbers from 0 to n-1 (where n is the count of values), by that you can access your desired value with the indexes [0][0]. See more here
http://codepad.org/YXu6884R
Here you go. See above for proof. The methodology from #azat is not explicit enough and is prone to risk if the elements of the array or sub array are re-arranged or if the key value for the super array changes.
$my_array = array( 123654 => array( 0 => '123456789123456789', 1 => '1', 2 => '06/24/2011', 3 => '06/24/2012', 4 => '12355.44', 5 => '55321.55' ) );
echo $my_array['123654'][0];
Try
$first = array_shift(array_values($array));
http://php.net/manual/en/function.array-shift.php
Good day everyone.
I have an regular array (this is the print_r result, the array can have from 1 to n positions):
Array
(
[1] => value1
[2] => value2
[3] => value3
)
I have another array defined elsewhere as:
$array_def['value1']['value2']['value3'] = array(
'fl' => 'field1',
'f2' => 'field2',
);
Using the first array result, how can i check if $array_def exists? In other words, i need to use a flat array values to check if a multidimensional array correspondence exists; keep in mind that the values can repeat in the first array, therefore flipping values with keys it's not an option as it will collide and remove duplicated values.
Thanks in advance.
You can do it this way:
$a = array(1=>'value1', 2=>'value2', 3=>'value3');
$array_def[$a[1]][$a[2]][$a[3]] = array(
'fl' => 'field1',
'f2' => 'field2',
);
I don't think there's any shortcut or special built-in function to do this.
Found the perfect function for you. returns not only exists, but position within a multi-dimensional array..
http://www.php.net/manual/en/function.array-search.php#47116
dated: 03-Nov-2004 11:13
too much to copy/paste
you can then loop over your flat array and foreach:
multi_array_search($search_value, $the_array)
I am learning php. In spite of so many examples on google, I am still confused about implementing arrays which are two dimensional and three dimensional. Can anyone explain, in simple terms, with an example please?
The easiest example for me was thinking of a SQL table as a multidimensional array.
The table might look like this:
ID | Name | Email
--------------------------
1 | John | john#email.com
2 | Jane | jane#email.com
And the array might look like this:
Array
(
[0] => Array
(
[0] => 1
[1] => John
[2] => john#email.com
)
[1] => Array
(
[0] => 2
[1] => Jane
[2] => jane#email.com
)
)
The table is turned into an array of arrays. Where each row is accessed by the first index and each column by the second index.
So If I wanted to get "Jane" I would use $array[1][1]
An associative array of that same table might look like this:
Array
(
[0] => Array
(
[ID] => 1
[Name] => John
[Email] => john#email.com
)
[1] => Array
(
[ID] => 2
[Name] => Jane
[Email] => jane#email.com
)
)
You would access "Jane" like $array[1]["Name"]
These are arrays which are nested in other arrays. Depending on how deep they are nested determines what dimensional they are.
Here is an example of a 1D and 2D array, respectively.
$arr =
array(
'item1' => 543,
654 => true,
'xas' => 0.54
);
// Accessing $arr[654] (returns true)
$arr2 = array(
array
(
'a' => 54,
'b' => 'Hello'
),
array
(
'itemx' => true,
954 => 'hello'
)
);
// Accessing $arr[0]['b'] (equal to 'Hello')
For a 3D array, you simply add another nested array into one of the 2nd level array items in the 2D array example.
There also is a very simple way to get started with multidimensional arrays.
Simply take a sheet and a pencil and start writing your multidimensional array down on paper first. It will help you a lot in the beginning.
It should look something like this.
ARRAY0 {
key0.0 => "value0.0",
key0.1 => "value0.1",
key0.2 => ARRAY1 {
key1.0 => "value1.0",
key1.1 => ARRAY2 {
key2.0 => "value2.0",
key2.1 => "value2.1",
},
key1.2 => "value1.2",
},
key0.3 => "value0.3",
};
This is just my way of visualizing the arrays you can come up with your own syntax if you want.
An array can have anything in it, from an integer to a string, to a full blown object, to another array.
Any array on its own is called a 1-dimensional array. If you think of it as a row of boxes, then it's a single row. If an array has another array in it then it's a 2-dimensional array: one of its boxes will be a column, adding another dimension.
$users = array() ;
$jim = array('Jim', 'Smith') ;
$users[] = $jim ;
//or in one step
$users = array(array('Jim', 'Smith')) ;
//then to access the first user:
$jim = $users[0];
//and his firstname:
$jimsname = $users[0][0] ;
//or
$jimsname = $jim[0] ;
You can access elements of the array and its nested arrays by indices, but you need to remember which numeric index corresponds to which piece of information. That's where you can use associative arrays, where the numeric indices are replaced by unique descriptive strings:
$users = array() ;
$jim = array(
'firstname' => 'Jim',
'lastname' => 'Smith'
) ;
$users['jim'] = $jim ;
//then to access jim:
$jim = $users['jim'];
//and his firstname:
$jimsname = $users['jim']['firstname'] ;
//or
$jimsname = $jim['firstname'] ;
That's pretty much it. You can see more here and in the manual
try this simply.
$anArray['abc'][1]['qwe']='this is a value';
$anArray['abc']['avs']='another value';
echo $anArray['abc'][1]['qwe'];
echo $anArray['abc']['avs'];
/*
Array is a bit different in PHP. You can think of array elements as single variables ($anArray['abc'][1]['qwe'] or $anArray['abc']['avs']). And you can create them like single variables. This is an addition to conventional arrays. Conventional way is also supported.
But what happens if you write : $anArray['abc']='something else';
$anArray['abc'] is just a string variable from that point. So you cannot (or may not as I didn't test it yet and practically everything is possible) access $anArray['abc'][1]['qwe'] anymore.
So try to think the elements like variables, first ;)
*/
I have an array with some value like this:
[Organization_id] => Array
(
[0] => 4
[1] => 4
[2] => 4
)
but i want some thing like this:
[Organization_id] => Array
(
[0] => 4
)
Thanks in advance..
If you don't care about the key to value association possibly messing up, you can use this:
$array = array_unique($array);
Although array_unique was mentioned twice now, I feel the answers failed to point out that you have to use the function on the nested array and not the array itself, so here is a usage example
$array = array( 'Organization_id' => array(4,4,4) );
$array['Organization_id'] = array_unique( $array['Organization_id'] );
print_r($array);
which will do what you want.