I have several associative arrays in PHP that looks like this:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
....
I want to create another associative array, using the serialized values of the previous arrays are used as the array keys. For example:
$newArray = array("data1's serialized key" => "someNewValue", ... );
Are serialized arrays suitable for being used as array keys?
Do they contain any unacceptable characters?
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Are serialized arrays suitable for being used as array keys?
Yup! As far as I know you can use serialized arrays as a key in another array. But the I cannot think of any use-case for this. :P
Do they contain any unacceptable characters?
No, until and unless you specify any unacceptable characters in the original array.
Do I need to do something more to the serialized string to make it acceptable as an array key (while still keeping its uniqueness)?
Nope.
So, you code would look like:
$data1 = array("foo" => "one", "animal" => "mice");
$data2 = array("foo" => "two", "animal" => "cats");
$serializedArrayKey1 = serialize($data1);
$serializedArrayKey2 = serialize($data2);
$newArray = array($serializedArrayKey1 => "Value for data1", ...);
Related
I have the following array that is supposed to only be keys:
$keys = ['mod_4_key'];
and the bigger array which contains a lot of information:
$big_array = [ 'mod_4_key' => ['old' => '', 'info' => ''], 'mod_5_key' => ..]
I would like to, based on what is inside $keys generate a new array with the information from $big_array, as such, if we are to compute the "non-difference" between the arrays, the output should be:
$final_array = [ 'mod_4_key' => ['old' => '', 'info' => '']]
I achieved this using a classic foreach but I was wondering if there was no in-built way to achieve this.
You may be better off with a simple foreach() loop, but there are probably several ways of achieving this.
This uses array_flip() on the $keys, so that you end up with another associative array, then use array_intersect_key() with the big array first.
$final_array = array_intersect_key($big_array, array_flip($keys));
I can define an array in PHP like this:
$array = array();
In C++, we have two kinds of array.
The first kind is a fixed size array, for example:
int arr[4]; // 4 ints, hardcoded size
The second kind is a dynamic sized array
std::vector<int> v; // can grow and shrink at runtime
What kind of array does PHP use? Are both kinds of arrays in PHP? If so, can you give me examples?
PHP is not as strict as C or C++. In PHP you don't need to specify the type of data to be placed in an array, you don't need to specify the array size either.
If you need to declare an array of integers in C++ you can do it like this:
int array[6];
This array is now bound to only contain integers. In PHP an array can contain just about everything:
$arr = array();
$arr[] = 1;
$arr[] = 2;
$arr[] = 3;
$arr[] = 4;
var_dump($arr); //Prints [1,2,3,4]
$arr[] = 'hello world'; //Adding a string. Completely valid code
$arr[] = 3.14; //Adding a float. This one is valid too
$arr[] = array(
'id' => 128,
'firstName' => 'John'
'lastName' => 'Doe'
); //Adding an associative array, also valid code
var_dump($arr); //prints [1,2,3,4,'hello world',3.14, [ id => 128, firstName => 'John', lastName => 'Doe']]
If you're coming from a C++ background it's best to view the PHP array as a generic vector that can store everything.
From php.net
An array in PHP is actually an ordered map. A map is a type that
associates values to keys. This type is optimized for several
different uses; it can be treated as an array, list (vector), hash
table (an implementation of a map), dictionary, collection, stack,
queue, and probably more. As array values can be other arrays, trees
and multidimensional arrays are also possible.
Basically there are three Usage patterns of array in PHP.
Indexed array: Arrays with sequential numeric index, such as 0, 1, 2, etc. Example:
$myarray = array();
$myarray[0] = "test data 1";
$myarray[1] = "test data 2";
$myarray[3] = "test data 3";
Associative array: This is the most frequently used type of PHP arrays whose elements are defined in key/value pair. Example:
$myarray = array();
$myarray["key1"] = "value 1";
$myarray["key2"] = "value 2";
$myarray["key3"] = "value 3";
Multidimensional array: Arrays whose elements may contains one or more arrays. There is no limit in the level of dimensions. Example:
$myarray = array();
$myarray[0] = array("data01","data02","data03");
$myarray[1] = array("data11","data12","data13");
For more details - Refer to PHP 5 Arrays.
PHP uses three kinds of array:
Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion.
Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are accessed using multiple indices.
Numeric Array Ex:
$numbers = array( 1, 2, 3, 4, 5);
Associative Array Ex:
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
Multidimensional Array Ex:
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
A php array, in C++ terms, is roughly:
std::map< std::experimental::any, std::experimental::any >
where std::experimental::any is a type that can hold basically anything. The php equivalent also can be sorted with the equivalent of <.
Well not quite -- closer to the truth is that a php array is an abstract interface that exposes much of the operations that the above map would provide in C++ (the C++ map is a concrete implementation).
Arrays with contiguous numeric keys stored in the Variant are treated much like a std::vector<Variant>, and under the interface the php system might even use vector<Variant> or something similar to store it, or even have two different internal details, one of which is for contiguous blocks of integer indexed data, and the other for sparse entries. (I don't know how php is implemented, but that is how I would do it)
PHP uses numeric, associative arrays, and multidimensional arrays. Arrays are dynamic in nature, and no size should be mentioned. Go through php.net/manual/en/language.types.array.php to find details.
I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));
if i have the following array:
array(
'var1' => 123,
'var2' => 234,
'var3' => 345
);
I would like to extract specific parts of this to build a new array i.e. var1 and var3.
The result i would be looking for is:
array(
'var1' => 123,
'var3' => 345
);
The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.
Is there a built in php function to do this?
Edit:
The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));
So, with your edit:
$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
You don't need a built in function to do this, try this :
$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array
// For each record in your initial array
foreach ($firstArray as $key => $value)
{
// If the key (ex : 'var1') is part of the desired keys
if (in_array($key, $this->keysToExtract)
{
$finalArray[$key] = $value; // Add to the new array
}
}
var_dump($finalArray);
Note that this is most likely the most efficient way to do this.
array(
[0]
name => 'joe'
size => 'large'
[1]
name => 'bill'
size => 'small'
)
I think i'm being thick, but to get the attributes of an array element if I know the value of one of the keys, I'm first looping through the elements to find the right one.
foreach($array as $item){
if ($item['name'] == 'joe'){
#operations on $item
}
}
I'm aware that this is probably very poor, but I am fairly new and am looking for a way to access this element directly by value. Or do I need the key?
Thanks,
Brandon
If searching for the exact same array it will work, not it you have other values in it:
<?php
$arr = array(
array('name'=>'joe'),
array('name'=>'bob'));
var_dump(array_search(array('name'=>'bob'),$arr));
//works: int(1)
$arr = array(
array('name'=>'joe','a'=>'b'),
array('name'=>'bob','c'=>'d'));
var_dump(array_search(array('name'=>'bob'),$arr));
//fails: bool(false)
?>
If there are other keys, there is no other way then looping as you already do. If you only need to find them by name, and names are unique, consider using them as keys when you create the array:
<?php
$arr = array(
'joe' => array('name'=>'joe','a'=>'b'),
'bob' => array('name'=>'bob','c'=>'d'));
$arr['joe']['a'] = 'bbb';
?>
Try array_search
$key = array_search('joe', $array);
echo $array[$key];
If you need to do operations on name, and name is unique within your array, this would be better:
array(
'joe'=> 'large',
'bill'=> 'small'
);
With multiple attributes:
array(
'joe'=>array('size'=>'large', 'age'=>32),
'bill'=>array('size'=>'small', 'age'=>43)
);
Though here you might want to consider a more OOP approach.
If you must use a numeric key, look at array_search
You can stick to your for loop. There are not big differences between it and other methods – the array has always to be traversed linearly. That said, you can use these functions to find array pairs with a certain value:
array_search, if you're there's only one element with that value.
array_keys, if there may be more than one.