php - push array into an array -(pushing both key and the array) - php

I am trying to add an array to an existing array. I am able to add the array using the array_push . The only problem is that when trying to add array that contains an array keys, it adds an extra array within the existing array.
It might be best if I show to you
foreach ($fields as $f)
{
if ($f == 'Thumbnail')
{
$thumnail = array('Thumbnail' => Assets::getProductThumbnail($row['id'] );
array_push($newrow, $thumnail);
}
else
{
$newrow[$f] = $row[$f];
}
}
The fields array above is part of an array that has been dynamically fed from an SQl query it is then fed into a new array called $newrow. However, to this $newrow array, I need to add the thumbnail array fields .
Below is the output ( using var_dump) from the above code. The only problem with the code is that I don't want to create a seperate array within the arrays. I just need it to be added to the array.
array(4) { ["Product ID"]=> string(7) "1007520"
["SKU"]=> string(5) "G1505"
["Name"]=> string(22) "150mm Oval Scale Ruler"
array(1) { ["Thumbnail"]=> string(77) "thumbnails/products/5036228.jpg" } }
I would really appreciate any advice.

All you really want is:
$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);

You can use array_merge function
$newrow = array_merge($newrow, $thumnail);

Alternatively, you can also assign it directly to $newrow:
if ($f == 'Thumbnail')
$newrow[$f] = Assets::getProductThumbnail($row['id']);
else
...
Or if you want your code to be shorter:
foreach($fields as $f)
$newrow[$f] = ($f == 'Thumbnail')? Assets::getProductThumbnail($row['id']) : $row[$f];
But if you're getting paid by number of lines in your code, don't do this, stay on your code :) j/k

Related

What is the correct syntax for detecting an empty 2D array in PHP?

What is the correct syntax to detect an empty 2 Dimensional array in PHP? I have attempted to do so myself using the functions "isset()" and "!empty()" for both "2dArray[0]" and "2dArray[0][0]", but even with an empty array the result comes back positive. Here is a snippet of code from one of the times where I tried this:
if(isset($strengths[0][0]) || isset($sizes[0][0]))
{
print_r($strengths[0][0]);
echo "<br>blah<br>";
print_r($sizes[0][0]);
}
Yet the arrays are both empty. Using print_r we can even see that the arrays return nothing. Here is a picture example of a different attempt using isset(2dArray[0]):
In the picture you can see the array is also empty again.
It's important to note that I can use 2dArray[1] perfectly; it detects that there there is no second row as expected, but that means I cannot have any instances where there is only 1 row in either 2D array because it is positioned at position 0 with nothing at position 1 to be detected anyway.
What am I doing wrong?
Edit 1:
The code:
var_dump($strengths[0][0]);
var_dump($sizes[0][0]);
returns:
array(0) { }
array(0) { }
and the code:
var_dump($strengths[0]);
var_dump($sizes[0]);
returns:
array(1) { [0]=> array(0) { } }
array(1) { [0]=> array(0) { } }
Edit 2:
This is my init:
$sizes[][] = array();
This is where data is set:
foreach($products as $product)
{
//product information
foreach($mods as $mod)
{
//mod information
//when array is empty $mods is empty
if ($modType == "SIZE")
{
$sizes[$si][0] = $modValue . $modValueSuffix;
$sizes[$si][1] = $modPrice;
$sizes[$si][2] = $modID;
$si++;
$strengthOrSize = true;
}
}
}
I believe I should have done $sizes[] = array(); for a 2D array. I overlooked this because it's such a short piece of code I did not give it much attention.
You can do this to detect if the sub array is empty:
$arr = [[]];
if (!count($arr[0])) {
// do stuff
}

Merge arrays with strings and delete repetitive values in PHP

From WP_Query I am dumping strings stored into separate arrays:
array(1) {
[0]=>
string(8) "Portugal"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(5) "Italy"
}
array(1) {
[0]=>
string(6) "Monaco"
}
array(1) {
[0]=>
string(5) "Spain"
}
array(1) {
[0]=>
string(9) "Lithuania"
}
I am trying to merge those arrays into one array, delete repetitive strings like "Spain" and get the number of unique values.
I was trying to use array_merge():
$tester = array();
foreach($array_string as $value) {
array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
But without any decent results, error telling that <b>Warning</b>: array_merge(): Argument #2 is not an array Could someone tell where I am missing the point? Many thanks for all possible help, will be looking forward.
The code posted in the question is almost good. The intention is correct but you missed out a simple thing: you initialize $tester with an empty array and then never add something to it. In the end, it is still empty and array_unique() has nothing to do but return an empty array too.
The error is in the line:
array_merge($tester, $value);
array_merge() does not change the arrays passed to it as argument. It returns a new array that your code ignores (instead of saving it into $tester).
This is how your code should look like:
$tester = array();
foreach($array_string as $value) {
$tester = array_merge($tester, $value);
}
$result = array_unique($tester);
print_r($result);
Solution #2
You can use call_user_func_array() to invoke array_merge() and pass the values of $array_string as arguments. The returned array contains duplicates; passing it to array_unique() removes them:
$result = array_unique(call_user_func_array('array_merge', $array_string));
Solution #3
A simpler (and possibly faster) way to accomplish the same thing is to use array_column() to get the values into an array and then pass it to array_unique(), of course:
$result = array_unique(array_column($array_string, 0));
This solution works only with PHP 5.5 or newer (the array_column() function doesn't exist in older versions.)
To get the number of unique strings in the merged array you will have to set empty array before WP_Query
$tester = array();
Than inside while loop of WP_Query every string is put into separate array and pushed to $tester
foreach((array)$array_string as $key=>$value[0]) {
array_push($tester,$value);
}
Unique values in array $tester is found using array_unique() functions that should be placed after WP_Query while loop.
$unique_array_string = array_unique($tester, SORT_REGULAR);
$unique_string_number = sizeof($unique_array_string);
You will create an array and will take key of the array for cities names like spain..etc And it will give different cities name always...
$data= array();
$data1 = array("Portugal");
$data2 = array("Spain");
$data3 = array("Italy");
$data4 = array("Monaco");
$data5 = array("Spain");
$data6 = array("Lithuania");
$merge = array_merge($data1, $data2,$data3,$data4,$data5,$data6);
$data = array();
foreach($merge as $value) {
$data[$value] = $value;
}
echo '<pre>',print_r($data),'</pre>';

How to get one part of a multidimensional array using php?

I have a problem with a multidimensional array, I want to save specific parts of an array to later show the information on the page but I just cant get it to work
this is the Array when I var_dump it:
array(1) {
["500040477"]=> array(1) {
["statistics"]=> array(1) {
["all"]=> array(1) {
["frags"]=> int(23816)
}
}
}
}
now I want to get the frags and be able to save the int in a extra array/variable
I tried a lot and nothing works even the "common" method to access it doesn't work :(
In the case showed in your example:
$frags = $nameOfYourArray["500040477"]["statistics"]["all"]["frags"];
For arrays with the first key with different name (instead of 500040477):
$arrayFirstkey = current($array);
$frags = $arrayFirstkey["statistics"]["all"]["frags"];
See current PHP function.
If you want to save specific parts of an array ,you can write your own function for this
//first param arra ,second param key
function findByKey($array,$k) {
if(isset($array[$k])) {
return $array[$k];
}
else {
if(is_array($array)) return findByKey(current($array),$k);
else return "Key don't exist";
}
}
You can use above function to get specific array value using key .As your question
findByKey($yourarray,"frags");

manipulate, delete or unset subarray of a multidimensional array [duplicate]

This question already has answers here:
How to extract specific array keys and values to another array?
(2 answers)
Closed 4 months ago.
I need help manipulating my two dimensional array. My array has many record sets with 2 columns of values and I'd like to manipulate the array so there is an array of many record sets with one column by converting one of my original columns as the key to the one column of values.
My Array:
[0]=>
[0]=> "48903"
[1]=> "SDFI"
[1]=>
[0]=> "2890"
[1]=> "DISL"
[2] =>
[0]=> "80890"
[1]=> "DISL"
...plus more
Intended array:
[0]=>
[48903]= "SDFI"
[2890]=>"DISL"
[80890] => "DISL"
...plus more
I've tried creating a new array with the intended keys and then unsetting the subarray but when the new array is vardumped at the end of script, it still shows that they subarray hasn't been removed.
my experimental codes
$newarr=array();
foreach($arr as $val => $rename){
$newarr[$rename[0]]= $rename;
}
foreach($newarr as $k => $v){
unset($v[0]); //does not remove/unset the extra column when newarr is var_dumped at the end of the script
$filter = array_filter($newarr, function($k) {
return $k == '1'; }); //or return $k !== 0; }) // other code to filter extra column that does not seem to work.
I think I came across a similar problem from someone else but they had 3 columns for each record set and wanted to reduce the number of columns to 2 and change the extra column as a key. However, I can't seem to locate that page. If anyone could find it and post a link, that would be great.
Any help would be great.. thank you in advance.
Try this:
<?php
// the function:
function arr2kv($arr) {
$res = array();
foreach($arr as $v) $res[$v[0]] = $v[1];
return $res;
}
// testing:
$n = array(
array("48903","SDFI"),
array("2890","DISL"),
array("80890","DISL")
);
print_r( arr2kv($n) );
/* // result:
Array
(
[48903] => SDFI
[2890] => DISL
[80890] => DISL
)
*/
Try this -
$newarr=array();
foreach($arr as $val => $rename){
$newarr[$rename[0]]= $rename[1];
}

How to convert an array of arrays or objects to an associative array?

I'm used to perl's map() function where the callback can assign both the key and the value, thus creating an associative array where the input was a flat array. I'm aware of array_fill_keys() which can be useful if all you want to do is create a dictionary-style hash, but what if you don't necessarily want all values to be the same? Obviously all things can be done with foreach iteration, but what other (possibly more elegant) methods exist?
Edit: adding an example to clarify the transformation. Please don't get hung up on the transformation, the question is about transforming a flat list to a hash where we can't assume that all the values will be the same.
$original_array: ('a', 'b', 'c', 'd')
$new_hash: ('a'=>'yes', 'b'=>'no', 'c'=>'yes', 'd'=>'no')
*note: the values in this example are arbitrary, governed by some business logic that is not really relevant to this question. For example, perhaps it's based on the even-oddness of the ordinal value of the key
Real-world Example
So, using an answer that was provided here, here is how you could parse through the $_POST to get a list of only those input fields that match a given criteria. This could be useful, for example, if you have a lot of input fields in your form, but a certain group of them must be processed together.
In this case I have a number of input fields that represent mappings to a database. Each of the input fields looks like this:
<input name="field-user_email" value="2" /> where each of this type of field is prefixed with "field-".
what we want to do is, first, get a list of only those input fields who actually start with "field-", then we want to create an associative array called $mapped_fields that has the extracted field name as the key and the actual input field's value as the value.
$mapped_fields = array_reduce( preg_grep( '/field-.+/', array_keys( $_POST ) ), function( $hash, $field ){ $hash[substr( $field, 6 )] = $_POST[$field]; return $hash; } );
Which outputs:
Array ( [date_of_birth] => 1 [user_email] => 2 [last_name] => 3 [first_name] => 4 [current_position] => 6 )
(So, just to forestall the naysayers, let me agree that this bit of compact code is arguably a lot less readable that a simple loop that iterates through $_POST and, for each key, checks to see if it has the prefix, and if so, pops it and its value onto an array)
I had the exact same problem some days ago. It is not possible using array_map, but array_reduce does the trick.
$arr = array('a','b','c','d');
$assoc_arr = array_reduce($arr, function ($result, $item) {
$result[$item] = (($item == 'a') || ($item == 'c')) ? 'yes' : 'no';
return $result;
}, array());
var_dump($assoc_arr);
result:
array(4) { ["a"]=> string(3) "yes" ["b"]=> string(2) "no" ["c"]=> string(3) "yes" ["d"]=> string(2) "no" }
As far as I know, it is completely impossible in one expression, so you may as well use a foreach loop, à la
$new_hash = array();
foreach($original_array as $item) {
$new_hash[$item] = 'something';
}
If you need it in one expression, go ahead and make a function:
function array_map_keys($callback, $array) {
$result = array();
foreach($array as $item) {
$r = $callback($item);
$result[$r[0]] = $r[1];
}
return $result;
}
This is a clarification on my comment in the accepted method. Hopefully easier to read. This is from a WordPress class, thus the $wpdb reference to write data:
class SLPlus_Locations {
private $dbFields = array('name','address','city');
public function MakePersistent() {
global $wpdb;
$dataArray = array_reduce($this->dbFields,array($this,'mapPropertyToField'));
$wpdb->insert('wp_store_locator',$dataArray);
}
private function mapPropertyToField($result,$property) {
$result[$property] = $this->$property;
return $result;
}
}
Obviously there is a bit more to the complete solution, but the parts relevant to array_reduce() are present. Easier to read and more elegant than a foreach or forcing the issue through array_map() plus a custom insert statement.
Nice!
A good use case of yield operator!
$arr = array('a','b','c','d');
$fct = function(array $items) {
foreach($items as $letter)
{
yield sprintf("key-%s",
$letter
) => "yes";
}
};
$newArr = iterator_to_array($fct($arr));
which gives:
array(4) {
'key-a' =>
string(3) "yes"
'key-b' =>
string(3) "yes"
'key-c' =>
string(3) "yes"
'key-d' =>
string(3) "yes"
}

Categories