PHP multiple values in one key of associative Array - php

I stuck with a problem: I have an array with IDs and want to assign theses IDs to a key of a associative array:
$newlinkcats = array( 'link_id' => $linkcatarray[0], $linkcatarray[1], $linkcatarray[2]);
this works fine, but I don't know how many entries in $linkcatarray. So I would like to loop or similar. But I don't know how.
no push, cause it is no array
no implode, cause it is no string
no =, cause it overrides the value before
Could anyone help?
Thanks
Jim

Why not just implode it ?
$newlinkcats = array(
'link_id' => implode(
',',
$linkcatarray
)
);
Or just do this:
// Suggested by Tularis
$newlinkcats = array(
'link_id' => $linkcatarray
);

If your $linkcatarray array is only comprised of the values you wish to assign to the link_id key, then you can simply point the key at that array:
$newlinkcats = array('link_id' => $linkcatarray);
If that array contains more values that you don't want included, then take a look at array_slice() to only grab the indexes you need:
// Grabs the first 3 values from $linkcatarray
$newlinkcats = array('link_id' => array_slice($linkcatarray, 0, 3));
If your desired indexes aren't contiguous, it may be easier to cherry-pick them and use a new array:
$newlinkcats = array('link_id' => array(
$linkcatarray[7],
$linkcatarray[13],
$linkcatarray[22],
// ...
));

Related

Multidimensional Array Not Echoing As Expected

I am setting this array manually:
$schools = array(
'Indiana University'=>array(
'initials'=>'IU',
'color'=>'red',
'directory'=>'indiana'
)
);
But it won't echo "IU" when I use:
echo $schools[0][0];
It does show correctly when I do:
print_r($schools);
I'm sure I'm messing up something dumb, but I have no idea what and I've been staring at it for hours. This array is actually part of a larger array with multiple universities, but when I trim it down to just this, it doesn't work.
PHP arrays support two types of keys - numerical and strings.
If you just push a value onto an array, it will use numerical keys by default. E.g.
$schools[] = 'Indiana University';
echo $schools[0]; // Indiana University
However, when you use string keys, you access the array values using the string key. E.g.
$schools = array(
'Indiana University' => array(
'initials' => 'IU',
'color' => 'red',
'directory' => 'indiana'
)
);
echo $schools['Indiana University']['initials']; // UI

PHP Prepend two elements to associative array

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));

echo value from multidimensional array

My PHP call is storing a table from mySQL with the following code.
while (mysqli_stmt_fetch($stmtMyCountTotals)) {
$stmtMyCountTotalsrow = array(
'IndividualUnitsCounted' => $IndividualUnitsCounted,
'IndividualUnitsAdjusted' => $IndividualUnitsAdjusted
);
$stmtMyCountTotalsrows[] = $stmtMyCountTotalsrow;
}
$stmtMyCountTotals->close();
I can not seem to pull a individual value from it. For Example If I want to pull a number from column 1 row 2. I know this is a basic question but I can not seem to find an answer.
This is a multidimensional array, so you would access it like so:
$row1col2 = $stmtMyCountTotalsrows[1][2]
$row2col1 = $stmtMyCountTotalsrows[2][1]
But since it is associative you would want:
$var = $stmtMyCountTotalsrows[1]['IndividualUnitsCounted'];
If you want to access it by column, then you would need to retrieve the column names first into an array:
$cols = array_keys($stmtMyCountTotalsrows[0]);
$var = $stmtMyCountTotalsrows[1][$cols[1]]
// ^ where this is the column number
There are no column numbers in your array, the second dimension is an associative array. So it should be:
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsCounted']
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsAdjusted']
You have an array inside another array. Or a multidimensional array. It looks like this:
Array(
0 => Array(
'IndividualUnitsCounted' => 'Something',
'IndividualUnitsAdjusted' => 'Something Else'
),
1 => Array(
'IndividualUnitsCounted' => 'Yet another something',
'IndividualUnitsAdjusted' => 'Final something'
),
...
...
)
If this array is called $stmtMyCountTotalsrows:
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something"
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something Else"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Yet another something"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Final something"
If you don't know the name of the columns beforehand, you could use current() for the first:
echo current($stmtMyCountTotalsrows[1]);
Alternatively, use array_slice():
echo current(array_slice(stmtMyCountTotalsrows, 0, 1));

Replace array key integers with string

$string = "php, photoshop, css";
I'm producing an array from the comma separated values above using the str_getcsv() function:
$array = str_getcsv($string);
Result:
Array ( [0] => php [1] => photoshop [2] => css )
How can I replace the key integers with a string tag for all elements like seen below?
Array ( [tag] => php [tag] => photoshop [tag] => css )
Edit: if not possible what alternative can I apply? I need the array keys to be identical for a dynamic query with multiple OR clauses
e.g.
SELECT * FROM ('posts') WHERE 'tag' LIKE '%php% OR 'tag' LIKE '%photoshop% OR 'tag' LIKE '%css%'
I'm producing the query via a function that uses the array key as a column name and value as criteria.
That is not possible. You can have only one item per key. But in your example, the string "tag" would be the key of every item.
The other way arround would work. So having an array like this:
array('php' => 'tag', 'photoshop' => 'tag', 'css' => 'tag');
This might help you, if you want to save the "type" of each entry in an array. But as all the entries of your array seems to be from the same type, just forget about the "tag" and only store the values in a numeric array.
Or you can use a multidimensional array within the numeric array to save the type:
array(
0 => array( 'type' => 'tag', 'value' => 'php' ),
1 => array( 'type' => 'tag', 'value' => 'photoshop' ),
2 => array( 'type' => 'tag', 'value' => 'css' )
);
But still using just an numeric array should be fine if all the entries have the same type. I can even think of a last one:
array(
'tag' => array('php', 'photoshop', 'css')
);
But even if I repeat myself: Just use an ordinary array and name it something like $tag!
BTW: explode(', ', %string) is the more common function to split a string.
To build SQL statement you might do something like this:
// ... inside you build function
if(is_array($value)){
$sql .= "'".$key."' LIKE '%."implode("%' OR '".$key."' LIKE '%", $value)."%'";
} else {
$sql .= "'".$key."' LIKE '%".$value."%'";
}
This might look confusing but it's much cleaner than runnig into two foreach-loops building the query.
That won't work. Your array keys have to be unique, or subsequent additions will simply overwrite the previous key.
As the others said, keys have to be unique. Otherwise, which element should be returned if you access $arr['tag']? If you now say "all of them", then create a nested array:
$array = array();
$array['tag'] = str_getcsv($string);
The value $array['tag'] will be another array (the one you already have) with numerical keys. This makes, because you have a list of tags and lists can be represented as arrays too.
Understanding arrays is very important if you want to work with PHP, so I suggest to read the array manual.
Assuming you know the size of your array beforehand
$tags = array("tag1","tag2","tag3");
$data = array("php","photoshop","css");
$myarray = array();
for ($i=0; $i<count($data); $i++) {
$myarray[$i] = array($data[$i], $tags[$i]);
}
Then
echo $myarray[0][0] . ", " . $myarray[0][1];
Outputs:
php, tag1

access array element by value

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.

Categories