PHP - Получение индекса элемента из массива

Я использую класс помощника посылки для преобразования объекта в / из участка.

См. Эту суть: https://gist.github.com/scallacs/f749a7385bcf75829a98d7b651efd02e

Использование очень просто:

Model model = new Model("HelloWorld");
// Create an object from the parcel model
Model createdFromParcel = ParcelTestHelper.createFromParcel(model, model.CREATOR);

// Do your assertions...
assertEquals(model.value, createdFromParcel.value);

Реализация:

import android.os.Parcel;
import android.os.Parcelable;

public class ParcelTestHelper {

    public static String DEFAULT_CREATOR_FIELD = "CREATOR";

    public static  T createFromParcel(T input, Parcelable.Creator creator) {
        Parcel parcel = toParcel(input);
        return fromParcel(parcel, creator);
    }

    public static  T createFromParcel(T input) throws NoSuchFieldException, IllegalAccessException {
        return createFromParcel(input, getCreator(input));
    }

    public static  Parcel toParcel(T input) {
        Parcel parcel = Parcel.obtain();
        input.writeToParcel(parcel, input.describeContents());
        parcel.setDataPosition(0);
        return parcel;
    }

    public static  Parcelable.Creator getCreator(T input) throws NoSuchFieldException, IllegalAccessException {
        return getCreator(input, DEFAULT_CREATOR_FIELD);
    }

    public static  Parcelable.Creator getCreator(T input, String field) throws NoSuchFieldException, IllegalAccessException {
        Object creator = input.getClass().getField(field).get(input);
        if (!(creator instanceof Parcelable.Creator)) {
            throw new InternalError("Should have field " + field + " instance of Parcelable.Creator");
        }
        return (Parcelable.Creator) creator;
    }

    public static  T fromParcel(Parcel parcel, Parcelable.Creator creator) {
        return creator.createFromParcel(parcel);
    }
}

24
задан Alex 21 September 2010 в 21:30
поделиться

2 ответа

function Index($index) {
    $Count = count($YOUR_ARRAY);
    if ($index <= $Count) {
        $Keys = array_keys($YOUR_ARRAY);
        $Value = array_values($YOUR_ARRAY);
        return $Keys[$index] . ' = ' . $Value[$index];
    } else {
        return "Out of the ring";
    }
}

echo 'Index : ' . Index(0);

Заменить ($ YOUR_ARRAY)

0
ответ дан 28 November 2019 в 22:41
поделиться

Нет способа получить позицию , которую вы действительно хотите.
Для ассоциативного массива, чтобы определить последнюю итерацию, вы можете использовать уже упомянутую переменную счетчика или сначала определить ключ последнего элемента:

end($array);
$last = key($array);
foreach($array as $key => value)
  if($key == $last) ....
-2
ответ дан 28 November 2019 в 22:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: