I have items visually:
array(
0 => '"abc","def",ghi', //"abc","def",ghi is just value. 0----N is the expected array
1 => '"jkl", ...',
);
My actual written code in use is, so this is the concern:
array(
'"abc","def",ghi', //"abc","def",ghi is just value. 0----N is the expected array
'"jkl", ...',
);
I want to fetch "abc", but need to ignore the rest ,"def",ghi
How would I do that with PHP?
Thanks for any pointers.
$firstitem=explode(',',$yourarray[0]);
or
explode(",", $yourarray[0], 2);//to limit the explode so the resulting array does not contain unwanted elements
$firstitem[0] will contain the first characters of the first element from yourarray including "
$exp = explode(',', $myArray[0]);
print $exp[0];
$v = array(
0 => '"abc","def",ghi', //"abc","def",ghi is just value. 0----N is the expected array
1 => '"jkl", ...',
);
$x = reset(explode(',', $v[0]));
this is it?
Related
I am new to this place and I have a question about PHP that I can't figure out.
What I am trying to do is create an array of strings, but that's not the problem. The problem is I have no idea how to get the only string that I need.
Example code:
$array = [];
$array[$game] = $string;
I want to keep creating strings for one single game but there will but more and more strings coming in the array from different games. I want to get only the ones from a single game, I don't know if you get what I'm talking about but I hope so because I'm frustrated that I can't figure out a way.
You have to create sub array for each game then set strings inside
// checking it sub array already not exits to not overwrite it
if( isset($array[$game]) ){
$array[$game] = array();
}
then only insert your string inside it
$array[$game][] = $string1;
$array[$game][] = $string2;
...
as result you will have
array('somegame' => array(
0 => "some game string 1",
1 => "some game string 2",
...
)
)
Your question is too simple.
You are already appending the strings to array by the key of game id.
$array = [];
$array[$game] = $string;
So, your array will look like:
array(
1 => array('string 1', 'string 2'),
2 => array('string 3', 'string 4'),
3 => array('string 5', 'string 6'),
//..... and more
)
Where keys 1, 2 and 3 are the game ids.
If you want to retrieve the keys in case of game ids 1 and 2:
$game = 1;
$gameStringsOne = $arr[$game];
$game = 2;
$gameStringsTwo = $arr[$game];
Use multi-dimensional array like
$array = [];
$array[$game] = [ $string1, $string2 ];
Read the docs Use a multi-dimentional array, push strings to an array and then assign that to another array, that way you can have multiple strings to a game
<?php
$stringArray = array("str","str2");
// if needed do array_push($stringArray,"str3","str4");
array_push($gamelist['game'], $stringArray);
?>
get an array of strings when acessing game from gamelist
read more
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));
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],
// ...
));
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));
I am new to using multidimensional arrays with php, I have tried to stay away from them because they confused me, but now the time has come that I put them to good use. I have been trying to understand how they work and I am just not getting it.
What I am trying to do is populate results based on a string compare function, once I find some match to an 'item name', I would like the first slot to contain the 'item name', then I would like to increment the priority slot by 1.
So when when I'm all done populating my array, it is going to have a variety of different company names, each with their respective priority...
I am having trouble understanding how to declare and manipulate the following array:
$matches = array(
'name'=>array('somename'),
'priority'=>array($priority_level++)
);
So, in what you have, your variable $matches will point to a keyed array, the 'name' element of that array will be an indexed array with 1 entry 'somename', there will be a 'priority' entry with a value which is an indexed array with one entry = $priority_level.
I think, instead what you probably want is something like:
$matches[] = array(name => 'somename', $priority => $priority_level++);
That way, $matches is an indexed array, where each index holds a keyed array, so you could address them as:
$matches[0]['name'] and $matches[0]['priority'], which is more logical for most people.
Multi-dimensional arrays are easy. All they are is an array, where the elements are other arrays.
So, you could have 2 separate arrays:
$name = array('somename');
$priority = array(1);
Or you can have an array that has these 2 arrays as elements:
$matches = array(
'name' => array('somename'),
'priority' => array(1)
);
So, using $matches['name'] would be the same as using $name, they are both arrays, just stored differently.
echo $name[0]; //'somename';
echo $matches['name'][0]; //'somename';
So, to add another name to the $matches array, you can do this:
$matches['name'][] = 'Another Name';
$matches['priority'][] = 2;
print_r($matches); would output:
Array
(
[name] => Array
(
[0] => somename
[1] => Another Name
)
[priority] => Array
(
[0] => 1
[1] => 2
)
)
In this case, could this be also a solution with a single dimensional array?
$matches = array(
'company_1' => 0,
'company_2' => 0,
);
if (isset($matches['company_1'])) {
++$matches['company_1'];
} else {
$matches['company_1'] = 1;
}
It looks up whether the name is already in the list. If not, it sets an array_key for this value. If it finds an already existing value, it just raises the "priority".
In my opinion, an easier structure to work with would be something more like this one:
$matches = array(
array( 'name' => 'somename', 'priority' => $priority_level_for_this_match ),
array( 'name' => 'someothername', 'priority' => $priority_level_for_that_match )
)
To fill this array, start by making an empty one:
$matches = array();
Then, find all of your matches.
$match = array( 'name' => 'somename', 'priority' => $some_priority );
To add that array to your matches, just slap it on the end:
$matches[] = $match;
Once it's filled, you can easily iterate over it:
foreach($matches as $k => $v) {
// The value in this case is also an array, and can be indexed as such
echo( $v['name'] . ': ' . $v['priority'] . '<br>' );
}
You can also sort the matched arrays according to the priority:
function cmp($a, $b) {
if($a['priority'] == $b['priority'])
return 0;
return ($a['priority'] < $b['priority']) ? -1 : 1;
}
usort($matches, 'cmp');
(Sourced from this answer)
$matches['name'][0] --> 'somename'
$matches['priority'][0] ---> the incremented $priority_level value
Like David said in the comments on the question, it sounds like you're not using the right tool for the job. Try:
$priorities = array();
foreach($companies as $company) {
if (!isset($priorities[$company])) { $priorities[$company] = 0; }
$priorities[$company]++;
}
Then you can access the priorities by checking $priorities['SomeCompanyName'];.